<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/Frog_16px_1177822_easyicon.net.ico">
  <link rel="mask-icon" href="/images/Frog_32px_1177822_easyicon.net.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"hxy1997.xyz","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"输入关键字","hits_empty":"没有找到与「${query}」相关搜索","hits_stats":"${hits} 条相关记录，共耗时 ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="常见设计模式1.为什么要学习设计模式？在许多访谈中，你可能会遇到很多面向对象编程中的接口，抽象类，代理和以及其他与设计模式相关的问题。 一旦了解了设计模式，它会让你轻松应对任何访谈，并可以在你的项目中应用这些特性。在应用程序中实现设计模式已经得到验证和测试。 为了使应用程序具有可扩展性，可靠性和易维护性，应该编写符合设计模式的代码。 2.什么是设计模式。设计模式是我们每天编程遇到的问题的可重用解决">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式">
<meta property="og:url" content="https://hxy1997.xyz/2020/10/20/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/index.html">
<meta property="og:site_name" content="hxy的博客">
<meta property="og:description" content="常见设计模式1.为什么要学习设计模式？在许多访谈中，你可能会遇到很多面向对象编程中的接口，抽象类，代理和以及其他与设计模式相关的问题。 一旦了解了设计模式，它会让你轻松应对任何访谈，并可以在你的项目中应用这些特性。在应用程序中实现设计模式已经得到验证和测试。 为了使应用程序具有可扩展性，可靠性和易维护性，应该编写符合设计模式的代码。 2.什么是设计模式。设计模式是我们每天编程遇到的问题的可重用解决">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-10-19T16:00:00.000Z">
<meta property="article:modified_time" content="2020-10-25T06:02:29.749Z">
<meta property="article:author" content="hxy">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://hxy1997.xyz/2020/10/20/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>设计模式 | hxy的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="hxy的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">hxy的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Mia san Mia!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/huxingyi1997" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://hxy1997.xyz/2020/10/20/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/Robben.gif">
      <meta itemprop="name" content="hxy">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="hxy的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          设计模式
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-10-20 00:00:00" itemprop="dateCreated datePublished" datetime="2020-10-20T00:00:00+08:00">2020-10-20</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-10-25 14:02:29" itemprop="dateModified" datetime="2020-10-25T14:02:29+08:00">2020-10-25</time>
              </span>

          
            <span class="post-meta-item" title="热度" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">热度：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2020/10/20/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2020/10/20/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="常见设计模式"><a href="#常见设计模式" class="headerlink" title="常见设计模式"></a>常见设计模式</h1><h2 id="1-为什么要学习设计模式？"><a href="#1-为什么要学习设计模式？" class="headerlink" title="1.为什么要学习设计模式？"></a>1.为什么要学习设计模式？</h2><p>在许多访谈中，你可能会遇到很多面向对象编程中的接口，抽象类，代理和以及其他与设计模式相关的问题。 一旦了解了设计模式，它会让你轻松应对任何访谈，并可以在你的项目中应用这些特性。在应用程序中实现设计模式已经得到验证和测试。</p>
<p>为了使应用程序具有可扩展性，可靠性和易维护性，应该编写符合设计模式的代码。</p>
<h2 id="2-什么是设计模式。"><a href="#2-什么是设计模式。" class="headerlink" title="2.什么是设计模式。"></a>2.什么是设计模式。</h2><p>设计模式是我们每天编程遇到的问题的可重用解决方案。</p>
<p>设计模式主要是为了解决对象的生成和整合问题。</p>
<p>换句话说，设计模式可以作为可应用于现实世界编程问题的模板。</p>
<h2 id="3-设计模式的发展历史"><a href="#3-设计模式的发展历史" class="headerlink" title="3.设计模式的发展历史"></a>3.设计模式的发展历史</h2><p>设计模式的概念是由四人帮（《设计模式（可复用面向对象软件的基础）》的四位作者）提出。</p>
<p>四人帮把这本书分成两部分：</p>
<p>第一部分解释面向对象编程的优缺点。</p>
<p>第二部分是关于 23 个经典设计模式的演变。</p>
<p>自提出设计模式概念后，四人帮设计模式在软件开发生命周期中发挥了重要作用。</p>
<h2 id="4-设计模式分类"><a href="#4-设计模式分类" class="headerlink" title="4.设计模式分类"></a>4.设计模式分类</h2><p>根据实际应用中遇到的不同问题，四人帮将设计模式分为三种类型。</p>
<ul>
<li>创建型模式</li>
<li>结构型模式</li>
<li>行为型模式</li>
</ul>
<p>接下来将概述属于这三种类型的 23 种设计模式的主要概念。</p>
<span id="more"></span>

<h1 id="一、基础篇"><a href="#一、基础篇" class="headerlink" title="一、基础篇"></a>一、基础篇</h1><h2 id="this、new、bind、call、apply"><a href="#this、new、bind、call、apply" class="headerlink" title="this、new、bind、call、apply"></a>this、new、bind、call、apply</h2><h3 id="1-this-指向的类型"><a href="#1-this-指向的类型" class="headerlink" title="1. this 指向的类型"></a><strong>1. this 指向的类型</strong></h3><h4 id="this-在函数的指向有以下几种场景："><a href="#this-在函数的指向有以下几种场景：" class="headerlink" title="this 在函数的指向有以下几种场景："></a><strong>this 在函数的指向有以下几种场景：</strong></h4><ul>
<li>作为构造函数被 new 调用；</li>
<li>作为对象的方法使用；</li>
<li>作为函数直接调用；</li>
<li>被 <code>call</code>、<code>apply</code>、<code>bind</code> 调用；</li>
<li>箭头函数中的 <code>this</code>；</li>
</ul>
<h4 id="1-1-new-绑定"><a href="#1-1-new-绑定" class="headerlink" title="1.1 new 绑定"></a><strong>1.1 new 绑定</strong></h4><blockquote>
<p>函数如果作为构造函数使用 <code>new</code> 调用时， <code>this</code> 绑定的是新创建的构造函数的实例。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Foo</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = <span class="keyword">new</span> Foo()       <span class="comment">// 输出: Foo 实例，this 就是 bar</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>实际上使用 <code>new</code> 调用构造函数时，会依次执行下面的操作：</p>
</blockquote>
<ul>
<li>创建一个新对象；</li>
<li>构造函数的 <code>prototype</code> 被赋值给这个新对象的 <code>__proto__</code>；</li>
<li>将新对象赋给当前的 <code>this</code>；</li>
<li>执行构造函数；</li>
<li>如果函数没有返回其他对象，那么 <code>new</code> 表达式中的函数调用会自动返回这个新对象，如果返回的不是对象将被忽略；</li>
</ul>
<h4 id="1-2-显式绑定"><a href="#1-2-显式绑定" class="headerlink" title="1.2 显式绑定"></a><strong>1.2 显式绑定</strong></h4><blockquote>
<p>通过 <code>call</code>、<code>apply</code>、<code>bind</code> 我们可以修改函数绑定的 <code>this</code>，使其成为我们指定的对象。通过这些方法的第一个参数我们可以显式地绑定 <code>this</code>。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">name, price</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.name = name</span><br><span class="line">    <span class="built_in">this</span>.price = price</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Food</span>(<span class="params">category, name, price</span>) </span>&#123;</span><br><span class="line">    foo.call(<span class="built_in">this</span>, name, price)       <span class="comment">// call 方式调用</span></span><br><span class="line">    <span class="comment">// foo.apply(this, [name, price])    // apply 方式调用</span></span><br><span class="line">    <span class="built_in">this</span>.category = category</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> Food(<span class="string">&#x27;食品&#x27;</span>, <span class="string">&#x27;汉堡&#x27;</span>, <span class="string">&#x27;5块钱&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 浏览器中输出: &#123;name: &quot;汉堡&quot;, price: &quot;5块钱&quot;, category: &quot;食品&quot;&#125;</span></span><br><span class="line">call 和 apply 的区别是 call 方法接受的是参数列表，而 apply 方法接受的是一个参数数组。</span><br><span class="line"></span><br><span class="line">func.call(thisArg, arg1, arg2, ...)        <span class="comment">// call 用法</span></span><br><span class="line">func.apply(thisArg, [arg1, arg2, ...])     <span class="comment">// apply 用法</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>而 <code>bind</code> 方法是设置 <code>this</code> 为给定的值，并返回一个新的函数，且在调用新函数时，将给定参数列表作为原函数的参数序列的前若干项。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">func.bind(thisArg[, arg1[, arg2[, ...]]])    <span class="comment">// bind 用法</span></span><br></pre></td></tr></table></figure>

<p>举个例子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> food = &#123;</span><br><span class="line">    name: <span class="string">&#x27;汉堡&#x27;</span>,</span><br><span class="line">    price: <span class="string">&#x27;5块钱&#x27;</span>,</span><br><span class="line">    getPrice: <span class="function"><span class="keyword">function</span>(<span class="params">place</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(place + <span class="built_in">this</span>.price)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">food.getPrice(<span class="string">&#x27;KFC &#x27;</span>)   <span class="comment">// 浏览器中输出: &quot;KFC 5块钱&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> getPrice1 = food.getPrice.bind(&#123; <span class="attr">name</span>: <span class="string">&#x27;鸡腿&#x27;</span>, <span class="attr">price</span>: <span class="string">&#x27;7块钱&#x27;</span> &#125;, <span class="string">&#x27;肯打鸡 &#x27;</span>)</span><br><span class="line">getPrice1()       <span class="comment">// 浏览器中输出: &quot;肯打鸡 7块钱&quot;</span></span><br><span class="line">关于 bind 的原理，我们可以使用 apply 方法自己实现一个 bind 看一下：</span><br><span class="line"></span><br><span class="line"><span class="comment">// ES5 方式</span></span><br><span class="line"><span class="built_in">Function</span>.prototype.bind = <span class="built_in">Function</span>.prototype.bind || <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> self = <span class="built_in">this</span></span><br><span class="line">    <span class="keyword">let</span> rest1 = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>)</span><br><span class="line">    <span class="keyword">let</span> context = rest1.shift()</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> rest2 = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>)</span><br><span class="line">        <span class="keyword">return</span> self.apply(context, rest1.concat(rest2))</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ES6 方式</span></span><br><span class="line"><span class="built_in">Function</span>.prototype.bind = <span class="built_in">Function</span>.prototype.bind || <span class="function"><span class="keyword">function</span>(<span class="params">...rest1</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> self = <span class="built_in">this</span></span><br><span class="line">    <span class="keyword">const</span> context = rest1.shift()</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...rest2</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> self.apply(context, [...rest1, ...rest2])</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>ES6</code> 方式用了一些 <code>ES6</code> 的知识比如 <code>rest</code> 参数、数组解构</p>
</blockquote>
<p><strong>注意：</strong> 如果你把 <code>null</code> 或 <code>undefined</code> 作为 <code>this</code> 的绑定对象传入 <code>call</code>、<code>apply</code>、<code>bind</code>，这些值在调用时会被忽略，实际应用的是默认绑定规则。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">&#x27;hello&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo.call(<span class="literal">null</span>)         <span class="comment">// 浏览器中输出: &quot;hello&quot;</span></span><br></pre></td></tr></table></figure>

<p><code>bind(this)</code>链式调用，实际上后几项未执行，实质上 <code>this</code> 指向第一个绑定</p>
<h4 id="1-3-隐式绑定"><a href="#1-3-隐式绑定" class="headerlink" title="1.3 隐式绑定"></a>1.3 隐式绑定</h4><blockquote>
<p>函数是否在某个上下文对象中调用，如果是的话 <code>this</code> 绑定的是那个上下文对象。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">&#x27;hello&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a: <span class="string">&#x27;world&#x27;</span>,</span><br><span class="line">    foo: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">obj.foo()       <span class="comment">// 浏览器中输出: &quot;world&quot;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>上面代码中，<code>foo</code> 方法是作为对象的属性调用的，那么此时 <code>foo</code> 方法执行时，<code>this</code> 指向 <code>obj</code> 对象。也就是说，此时 <code>this</code> 指向调用这个方法的对象，如果嵌套了多个对象，那么指向最后一个调用这个方法的对象：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">&#x27;hello&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a: <span class="string">&#x27;world&#x27;</span>,</span><br><span class="line">    b:&#123;</span><br><span class="line">        a:<span class="string">&#x27;China&#x27;</span>,</span><br><span class="line">        foo: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">obj.b.foo()      <span class="comment">// 浏览器中输出: &quot;China&quot;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>最后一个对象是 <code>obj</code> 上的 <code>b</code>，那么此时 <code>foo</code> 方法执行时，其中的 <code>this</code> 指向的就是 <code>b</code> 对象。</p>
</blockquote>
<h4 id="1-4-默认绑定"><a href="#1-4-默认绑定" class="headerlink" title="1.4 默认绑定"></a><strong>1.4 默认绑定</strong></h4><blockquote>
<p>函数独立调用，直接使用不带任何修饰的函数引用进行调用，也是上面几种绑定途径之外的方式。非严格模式下 this 绑定到全局对象（浏览器下是 <code>winodw</code>，<code>node</code> 环境是 <code>global</code>），严格模式下 <code>this</code> 绑定到 <code>undefined</code> （因为严格模式不允许 <code>this</code> 指向全局对象）。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">&#x27;hello&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="string">&#x27;world&#x27;</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo()             <span class="comment">// 相当于执行 window.foo()</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 浏览器中输出: &quot;hello&quot;</span></span><br><span class="line"><span class="comment">// 浏览器中输出: Window 对象</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>上面代码中，变量 <code>a</code> 被声明在全局作用域，成为全局对象 <code>window</code> 的一个同名属性。函数 <code>foo</code> 被执行时，<code>this</code> 此时指向的是全局对象，因此打印出来的 <code>a</code> 是全局对象的属性。</p>
</blockquote>
<p>注意有一种情况：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">&#x27;hello&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a: <span class="string">&#x27;world&#x27;</span>,</span><br><span class="line">    foo: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = obj.foo</span><br><span class="line"></span><br><span class="line">bar()              <span class="comment">// 浏览器中输出: &quot;hello&quot;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>此时 <code>bar</code> 函数，也就是 <code>obj</code> 上的 <code>foo</code> 方法为什么又指向了全局对象呢，是因为 <code>bar</code> 方法此时是作为函数独立调用的，所以此时的场景属于默认绑定，而不是隐式绑定。这种情况和把方法作为回调函数的场景类似：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">&#x27;hello&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a: <span class="string">&#x27;world&#x27;</span>,</span><br><span class="line">    foo: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">func</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    fn()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func(obj.foo)              <span class="comment">// 浏览器中输出: &quot;hello&quot;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>参数传递实际上也是一种隐式的赋值，只不过这里 <code>obj.foo</code> 方法是被隐式赋值给了函数 <code>func</code> 的形参 <code>fn</code>，而之前的情景是自己赋值，两种情景实际上类似。这种场景我们遇到的比较多的是 <code>setTimeout</code> 和 <code>setInterval</code>，如果回调函数不是箭头函数，那么其中的 <code>this</code> 指向的就是全局对象.</li>
<li>其实我们可以把默认绑定当作是隐式绑定的特殊情况，比如上面的 <code>bar()</code>，我们可以当作是使用 <code>window.bar()</code> 的方式调用的，此时 bar 中的 <code>this</code> 根据隐式绑定的情景指向的就是 <code>window</code>。</li>
</ul>
<h3 id="2-this-绑定的优先级"><a href="#2-this-绑定的优先级" class="headerlink" title="2. this 绑定的优先级"></a><strong>2. this 绑定的优先级</strong></h3><blockquote>
<p><code>this</code> 存在多个使用场景，那么多个场景同时出现的时候，<code>this</code> 到底应该如何指向呢。这里存在一个优先级的概念，<code>this</code> 根据优先级来确定指向。<strong>优先级：new 绑定 &gt; 显示绑定 &gt; 隐式绑定 &gt; 默认绑定</strong></p>
</blockquote>
<p><strong>所以 this 的判断顺序：</strong></p>
<ul>
<li><code>new</code> 绑定： 函数是否在 <code>new</code> 中调用？如果是的话 <code>this</code> 绑定的是新创建的对象；</li>
<li>显式绑定： 函数是否是通过 <code>bind</code>、<code>call</code>、<code>apply</code> 调用？如果是的话，<code>this</code> 绑定的是指定的对象；</li>
<li>隐式绑定： 函数是否在某个上下文对象中调用？如果是的话，<code>this</code> 绑定的是那个上下文对象；</li>
<li>如果都不是的话，使用默认绑定。如果在严格模式下，就绑定到 <code>undefined</code>，否则绑定到全局对象；</li>
</ul>
<h3 id="3-箭头函数中的-this"><a href="#3-箭头函数中的-this" class="headerlink" title="3. 箭头函数中的 this"></a><strong>3. 箭头函数中的 this</strong></h3><ul>
<li>箭头函数 是根据其声明的地方来决定 <code>this</code> 的</li>
<li>箭头函数的 <code>this</code> 绑定是无法通过 <code>call</code>、<code>apply</code>、<code>bind</code> 被修改的，且因为箭头函数没有构造函数 <code>constructor</code>，所以也不可以使用 new 调用，即不能作为构造函数，否则会报错。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">&#x27;hello&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a: <span class="string">&#x27;world&#x27;</span>,</span><br><span class="line">    foo: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">obj.foo()             <span class="comment">// 浏览器中输出: &quot;hello&quot;</span></span><br></pre></td></tr></table></figure>

<h3 id="4-一个-this-的小练习"><a href="#4-一个-this-的小练习" class="headerlink" title="4. 一个 this 的小练习"></a><strong>4. 一个 this 的小练习</strong></h3><p>用一个小练习来实战一下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">20</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a: <span class="number">40</span>,</span><br><span class="line">    foo:<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">    </span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">func</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="built_in">this</span>.a = <span class="number">60</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        func.prototype.a = <span class="number">50</span></span><br><span class="line">        <span class="keyword">return</span> func</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = obj.foo()        <span class="comment">// 浏览器中输出: 20</span></span><br><span class="line">bar()                      <span class="comment">// 浏览器中输出: 60</span></span><br><span class="line"><span class="keyword">new</span> bar()                  <span class="comment">// 浏览器中输出: 60</span></span><br></pre></td></tr></table></figure>

<p>稍微解释一下：</p>
<ul>
<li><code>var a = 20</code> 这句在全局变量 <code>window</code> 上创建了个属性 <code>a</code> 并赋值为 <code>20</code>；</li>
<li>首先执行的是 <code>obj.foo()</code>，这是一个箭头函数，箭头函数不创建新的函数作用域直接沿用语句外部的作用域，因此 <code>obj.foo()</code> 执行时箭头函数中 <code>this</code> 是全局 <code>window</code>，首先打印出 window 上的属性 a 的值 20，箭头函数返回了一个原型上有个值为 <code>50</code> 的属性 <code>a</code> 的函数对象 <code>func</code> 给 <code>bar</code>；</li>
<li>继续执行的是 <code>bar()</code>，这里执行的是刚刚箭头函数返回的闭包 <code>func</code>，其内部的 <code>this</code> 指向 <code>window</code>，因此 <code>this.a</code> 修改了 <code>window.a</code> 的值为 <code>60</code> 并打印出来；</li>
<li>然后执行的是 <code>new bar()</code>，根据之前的表述，<code>new</code> 操作符会在 <code>func</code> 函数中创建一个继承了 <code>func</code> 原型的实例对象并用 <code>this</code> 指向它，随后 <code>this.a = 60</code> 又在实例对象上创建了一个属性 <code>a</code>，在之后的打印中已经在实例上找到了属性 <code>a</code>，因此就不继续往对象原型上查找了，所以打印出第三个 <code>60</code>；</li>
<li>如果把上面例子的箭头函数换成普通函数呢，结果会是什么样？</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">20</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a: <span class="number">40</span>,</span><br><span class="line">    foo: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">func</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="built_in">this</span>.a = <span class="number">60</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        func.prototype.a = <span class="number">50</span></span><br><span class="line">        <span class="keyword">return</span> func</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = obj.foo()        <span class="comment">// 浏览器中输出: 40</span></span><br><span class="line">bar()                      <span class="comment">// 浏览器中输出: 60</span></span><br><span class="line"><span class="keyword">new</span> bar()                  <span class="comment">// 浏览器中输出: 60</span></span><br></pre></td></tr></table></figure>

<h2 id="闭包与高阶函数"><a href="#闭包与高阶函数" class="headerlink" title="闭包与高阶函数"></a>闭包与高阶函数</h2><h3 id="1-闭包"><a href="#1-闭包" class="headerlink" title="1. 闭包"></a><strong>1. 闭包</strong></h3><h4 id="1-1-什么是闭包"><a href="#1-1-什么是闭包" class="headerlink" title="1.1 什么是闭包"></a><strong>1.1 什么是闭包</strong></h4><blockquote>
<p>当函数可以记住并访问所在的词法作用域时，就产生了闭包，即使函数是在当前词法作用域之外执行。</p>
</blockquote>
<p>我们首先来看一个闭包的例子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">2</span></span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">bar</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(a)</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> bar</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> baz = foo()</span><br><span class="line"></span><br><span class="line">baz()            <span class="comment">// 输出: 2</span></span><br></pre></td></tr></table></figure>

<ul>
<li><code>foo</code> 函数传递出了一个函数 <code>bar</code>，传递出来的 <code>bar</code> 被赋值给 <code>baz</code> 并调用，虽然这时 <code>baz</code> 是在 <code>foo</code> 作用域外执行的，但 <code>baz</code> 在调用的时候可以访问到前面的 <code>bar</code> 函数所在的 <code>foo</code> 的内部作用域。</li>
<li>由于 <code>bar</code> 声明在 <code>foo</code> 函数内部，<code>bar</code> 拥有涵盖 <code>foo</code> 内部作用域的闭包，使得 <code>foo</code> 的内部作用域一直存活不被回收。一般来说，函数在执行完后其整个内部作用域都会被销毁，因为 <code>JavaScript</code> 的 <code>GC</code>（Garbage Collection）垃圾回收机制会自动回收不再使用的内存空间。但是闭包会阻止某些 <code>GC</code>，比如本例中 <code>foo()</code> 执行完，因为返回的 <code>bar</code> 函数依然持有其所在作用域的引用，所以其内部作用域不会被回收。</li>
<li>注意： 如果不是必须使用闭包，那么尽量避免创建它，因为闭包在处理速度和内存消耗方面对性能具有负面影响。</li>
</ul>
<h4 id="1-2-利用闭包实现结果缓存（备忘模式）"><a href="#1-2-利用闭包实现结果缓存（备忘模式）" class="headerlink" title="1.2 利用闭包实现结果缓存（备忘模式）"></a><strong>1.2 利用闭包实现结果缓存（备忘模式）</strong></h4><blockquote>
<p>备忘模式就是应用闭包的特点的一个典型应用。比如有个函数：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">a</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>多次运行 <code>add()</code> 时，每次得到的结果都是重新计算得到的，如果是开销很大的计算操作的话就比较消耗性能了，这里可以对已经计算过的输入做一个缓存。</li>
<li>所以这里可以利用闭包的特点来实现一个简单的缓存，在函数内部用一个对象存储输入的参数，如果下次再输入相同的参数，那就比较一下对象的属性，如果有缓存，就直接把值从这个对象里面取出来。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 备忘函数 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">memorize</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> cache = &#123;&#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> args = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>)</span><br><span class="line">        <span class="keyword">var</span> key = <span class="built_in">JSON</span>.stringify(args)</span><br><span class="line">        <span class="keyword">return</span> cache[key] || (cache[key] = fn.apply(fn, args))</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 复杂计算函数 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">a</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> adder = memorize(add)</span><br><span class="line"></span><br><span class="line">adder(<span class="number">1</span>)            <span class="comment">// 输出: 2    当前: cache: &#123; &#x27;[1]&#x27;: 2 &#125;</span></span><br><span class="line">adder(<span class="number">1</span>)            <span class="comment">// 输出: 2    当前: cache: &#123; &#x27;[1]&#x27;: 2 &#125;</span></span><br><span class="line">adder(<span class="number">2</span>)            <span class="comment">// 输出: 3    当前: cache: &#123; &#x27;[1]&#x27;: 2, &#x27;[2]&#x27;: 3 &#125;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>使用 <code>ES6</code> 的方式会更优雅一些：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 备忘函数 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">memorize</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> cache = &#123;&#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">const</span> key = <span class="built_in">JSON</span>.stringify(args)</span><br><span class="line">        <span class="keyword">return</span> cache[key] || (cache[key] = fn.apply(fn, args))</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 复杂计算函数 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">a</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> adder = memorize(add)</span><br><span class="line"></span><br><span class="line">adder(<span class="number">1</span>)            <span class="comment">// 输出: 2    当前: cache: &#123; &#x27;[1]&#x27;: 2 &#125;</span></span><br><span class="line">adder(<span class="number">1</span>)            <span class="comment">// 输出: 2    当前: cache: &#123; &#x27;[1]&#x27;: 2 &#125;</span></span><br><span class="line">adder(<span class="number">2</span>)            <span class="comment">// 输出: 3    当前: cache: &#123; &#x27;[1]&#x27;: 2, &#x27;[2]&#x27;: 3 &#125;</span></span><br></pre></td></tr></table></figure>

<p>稍微解释一下：</p>
<ul>
<li>备忘函数中用 <code>JSON.stringify</code> 把传给 <code>adder</code> 函数的参数序列化成字符串，把它当做 <code>cache</code> 的索引，将 <code>add</code> 函数运行的结果当做索引的值传递给 <code>cache</code>，这样 <code>adder</code> 运行的时候如果传递的参数之前传递过，那么就返回缓存好的计算结果，不用再计算了，如果传递的参数没计算过，则计算并缓存 <code>fn.apply(fn, args)</code>，再返回计算的结果。</li>
<li>当然这里的实现如果要实际应用的话，还需要继续改进一下，比如：</li>
<li>缓存不可以永远扩张下去，这样太耗费内存资源，我们可以只缓存最新传入的 <code>n</code> 个；</li>
<li>在浏览器中使用的时候，我们可以借助浏览器的持久化手段，来进行缓存的持久化，比如 <code>cookie</code>、<code>localStorage</code> 等；</li>
<li>这里的复杂计算函数可以是过去的某个状态，比如对某个目标的操作，这样把过去的状态缓存起来，方便地进行状态回退。</li>
<li>复杂计算函数也可以是一个返回时间比较慢的异步操作，这样如果把结果缓存起来，下次就可以直接从本地获取，而不是重新进行异步请求。</li>
</ul>
<blockquote>
<p>注意： <code>cache</code> 不可以是 <code>Map</code>，因为 <code>Map</code> 的键是使用 <code>===</code> 比较的，因此当传入引用类型值作为键时，虽然它们看上去是相等的，但实际并不是，比如 <code>[1]!==[1]</code>，所以还是被存为不同的键。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  X 错误示范</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">memorize</span>(<span class="params">fn</span>) </span>&#123;        </span><br><span class="line">    <span class="keyword">const</span> cache = <span class="keyword">new</span> <span class="built_in">Map</span>()</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cache.get(args) || cache.set(args, fn.apply(fn, args)).get(args)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">a</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> adder = memorize(add)</span><br><span class="line"></span><br><span class="line">adder(<span class="number">1</span>)    <span class="comment">// 2    cache: &#123; [ 1 ] =&gt; 2 &#125;</span></span><br><span class="line">adder(<span class="number">1</span>)    <span class="comment">// 2    cache: &#123; [ 1 ] =&gt; 2, [ 1 ] =&gt; 2 &#125;</span></span><br><span class="line">adder(<span class="number">2</span>)    <span class="comment">// 3    cache: &#123; [ 1 ] =&gt; 2, [ 1 ] =&gt; 2, [ 2 ] =&gt; 3 &#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="2-高阶函数"><a href="#2-高阶函数" class="headerlink" title="2. 高阶函数"></a><strong>2. 高阶函数</strong></h3><blockquote>
<p>高阶函数就是输入参数里有函数，或者输出是函数的函数。</p>
</blockquote>
<h4 id="2-1-函数作为参数"><a href="#2-1-函数作为参数" class="headerlink" title="2.1 函数作为参数"></a><strong>2.1 函数作为参数</strong></h4><blockquote>
<p>如果你用过 <code>setTimeout</code>、<code>setInterval</code>、<code>ajax</code> 请求，那么你已经用过高阶函数了，这是我们最常看到的场景：回调函数，因为它将函数作为参数传递给另一个函数。</p>
</blockquote>
<blockquote>
<p>比如 <code>ajax</code> 请求中，我们通常使用回调函数来定义请求成功或者失败时的操作逻辑：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$.ajax(<span class="string">&quot;/request/url&quot;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">result</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;请求成功！&quot;</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>在 <code>Array</code>、<code>Object</code>、<code>String</code> 等等基本对象的原型上有很多操作方法，可以接受回调函数来方便地进行对象操作。这里举一个很常用的 <code>Array.prototype.filter()</code> 方法，这个方法返回一个新创建的数组，包含所有回调函数执行后返回 <code>true</code> 或真值的数组元素。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> words = [<span class="string">&#x27;spray&#x27;</span>, <span class="string">&#x27;limit&#x27;</span>, <span class="string">&#x27;elite&#x27;</span>, <span class="string">&#x27;exuberant&#x27;</span>, <span class="string">&#x27;destruction&#x27;</span>, <span class="string">&#x27;present&#x27;</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> result = words.filter(<span class="function"><span class="keyword">function</span>(<span class="params">word</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> word.length &gt; <span class="number">6</span></span><br><span class="line">&#125;)  <span class="comment">// 输出: [&quot;exuberant&quot;, &quot;destruction&quot;, &quot;present&quot;]</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>回调函数还有一个应用就是钩子，如果你用过 Vue 或者 React 等框架，那么你应该对钩子很熟悉了，它的形式是这样的：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">callback</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// ... 一些操作</span></span><br><span class="line">    callback()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-2-函数作为返回值"><a href="#2-2-函数作为返回值" class="headerlink" title="2.2 函数作为返回值"></a><strong>2.2 函数作为返回值</strong></h4><blockquote>
<p>另一个经常看到的高阶函数的场景是在一个函数内部输出另一个函数，比如：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">bar</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>主要是利用闭包来保持着作用域：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> num = <span class="number">0</span></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">a</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> num = num + a</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> adder = add()</span><br><span class="line"></span><br><span class="line">adder(<span class="number">1</span>)     <span class="comment">// 输出: 1</span></span><br><span class="line">adder(<span class="number">2</span>)     <span class="comment">// 输出: 3</span></span><br></pre></td></tr></table></figure>

<h5 id="1-柯里化"><a href="#1-柯里化" class="headerlink" title="1. 柯里化"></a><strong>1. 柯里化</strong></h5><ul>
<li>柯里化（Currying），又称部分求值（Partial Evaluation），是把接受多个参数的原函数变换成接受一个单一参数（原函数的第一个参数）的函数，并且返回一个新函数，新函数能够接受余下的参数，最后返回同原函数一样的结果。</li>
<li>核心思想是把多参数传入的函数拆成单（或部分）参数函数，内部再返回调用下一个单（或部分）参数函数，依次处理剩余的参数。</li>
</ul>
<p><strong>柯里化有 3 个常见作用：</strong></p>
<ul>
<li>参数复用</li>
<li>提前返回</li>
<li>延迟计算/运行</li>
</ul>
<p>先来看看柯里化的通用实现：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ES5 方式</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">currying</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> rest1 = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>)</span><br><span class="line">    rest1.shift()</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> rest2 = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>)</span><br><span class="line">        <span class="keyword">return</span> fn.apply(<span class="literal">null</span>, rest1.concat(rest2))</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 只需要记住 ES6 方式</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">currying</span>(<span class="params">fn, ...rest1</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 把剩余参数与当前参数拼接</span></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...rest2</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> fn.apply(<span class="literal">null</span>, rest1.concat(rest2))</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>用它将一个 <code>sayHello</code> 函数柯里化试试：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 接上面</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sayHello</span>(<span class="params">name, age, fruit</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">console</span>.log(<span class="string">`我叫 <span class="subst">$&#123;name&#125;</span>,我 <span class="subst">$&#123;age&#125;</span> 岁了, 我喜欢吃 <span class="subst">$&#123;fruit&#125;</span>`</span>))</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> curryingShowMsg1 = currying(sayHello, <span class="string">&#x27;小明&#x27;</span>)</span><br><span class="line">curryingShowMsg1(<span class="number">22</span>, <span class="string">&#x27;苹果&#x27;</span>)           <span class="comment">// 输出: 我叫 小明,我 22 岁了, 我喜欢吃 苹果</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> curryingShowMsg2 = currying(sayHello, <span class="string">&#x27;小衰&#x27;</span>, <span class="number">20</span>)</span><br><span class="line">curryingShowMsg2(<span class="string">&#x27;西瓜&#x27;</span>)               <span class="comment">// 输出: 我叫 小衰,我 20 岁了, 我喜欢吃 西瓜</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>更高阶的用法参见：JavaScript 函数式编程技巧 - 柯里化</p>
</blockquote>
<h5 id="2-反柯里化"><a href="#2-反柯里化" class="headerlink" title="2. 反柯里化"></a><strong>2. 反柯里化</strong></h5><ul>
<li>柯里化是固定部分参数，返回一个接受剩余参数的函数，也称为部分计算函数，目的是为了缩小适用范围，创建一个针对性更强的函数。核心思想是把多参数传入的函数拆成单参数（或部分）函数，内部再返回调用下一个单参数（或部分）函数，依次处理剩余的参数。</li>
<li>而反柯里化，从字面讲，意义和用法跟函数柯里化相比正好相反，扩大适用范围，创建一个应用范围更广的函数。使本来只有特定对象才适用的方法，扩展到更多的对象。</li>
</ul>
<p>先来看看反柯里化的通用实现吧~</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ES5 方式</span></span><br><span class="line"><span class="built_in">Function</span>.prototype.unCurrying = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> self = <span class="built_in">this</span></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> rest = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Function</span>.prototype.call.apply(self, rest)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ES6 方式</span></span><br><span class="line"><span class="built_in">Function</span>.prototype.unCurrying = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> self = <span class="built_in">this</span></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...rest</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Function</span>.prototype.call.apply(self, rest)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 如果你觉得把函数放在 Function 的原型上不太好，也可以这样：</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// ES5 方式</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">unCurrying</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params">tar</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> rest = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>)</span><br><span class="line">        rest.shift()</span><br><span class="line">        <span class="keyword">return</span> fn.apply(tar, rest)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ES6 方式</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">unCurrying</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">tar, ...argu</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> fn.apply(tar, argu)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>简单说，函数柯里化就是对高阶函数的降阶处理，缩小适用范围，创建一个针对性更强的函数。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>(<span class="params">arg1, arg2</span>)              // =&gt; <span class="function"><span class="keyword">function</span>(<span class="params">arg1</span>)(<span class="params">arg2</span>)</span></span></span><br><span class="line"><span class="function"><span class="function"><span class="function"><span class="keyword">function</span>(<span class="params">arg1, arg2, arg3</span>)        // =&gt; <span class="function"><span class="keyword">function</span>(<span class="params">arg1</span>)(<span class="params">arg2</span>)(<span class="params">arg3</span>)</span></span></span></span></span><br><span class="line"><span class="function"><span class="function"><span class="function"><span class="function"><span class="function"><span class="keyword">function</span>(<span class="params">arg1, arg2, arg3, arg4</span>)  // =&gt; <span class="function"><span class="keyword">function</span>(<span class="params">arg1</span>)(<span class="params">arg2</span>)(<span class="params">arg3</span>)(<span class="params">arg4</span>)</span></span></span></span></span></span></span><br><span class="line"><span class="function"><span class="function"><span class="function"><span class="function"><span class="function"><span class="function"><span class="function"><span class="keyword">function</span>(<span class="params">arg1, arg2, ..., argn</span>)   // =&gt; <span class="function"><span class="keyword">function</span>(<span class="params">arg1</span>)(<span class="params">arg2</span>)…(<span class="params">argn</span>)</span></span></span></span></span></span></span></span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>而反柯里化就是反过来，增加适用范围，让方法使用场景更大。使用反柯里化, 可以把原生方法借出来，让任何对象拥有原生对象的方法。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">obj.func(arg1, arg2)        <span class="comment">// =&gt; func(obj, arg1, arg2)</span></span><br></pre></td></tr></table></figure>

<p><strong>可以这样理解柯里化和反柯里化的区别：</strong></p>
<ul>
<li>柯里化是在运算前提前传参，可以传递多个参数；</li>
<li>反柯里化是延迟传参，在运算时把原来已经固定的参数或者 this 上下文等当作参数延迟到未来传递。</li>
<li>更高阶的用法参见：JavaScript 函数式编程技巧 - 反柯里化</li>
</ul>
<h5 id="3-偏函数"><a href="#3-偏函数" class="headerlink" title="3. 偏函数"></a><strong>3. 偏函数</strong></h5><blockquote>
<p>偏函数是创建一个调用另外一个部分（参数或变量已预制的函数）的函数，函数可以根据传入的参数来生成一个真正执行的函数。其本身不包括我们真正需要的逻辑代码，只是根据传入的参数返回其他的函数，返回的函数中才有真正的处理逻辑比如：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> isType = <span class="function"><span class="keyword">function</span>(<span class="params">type</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">obj</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Object</span>.prototype.toString.call(obj) === <span class="string">`[object <span class="subst">$&#123;type&#125;</span>]`</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> isString = isType(<span class="string">&#x27;String&#x27;</span>)</span><br><span class="line"><span class="keyword">var</span> isFunction = isType(<span class="string">&#x27;Function&#x27;</span>)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这样就用偏函数快速创建了一组判断对象类型的方法~</p>
</blockquote>
<p><strong>偏函数和柯里化的区别：</strong></p>
<ul>
<li>柯里化是把一个接受 <code>n</code> 个参数的函数，由原本的一次性传递所有参数并执行变成了可以分多次接受参数再执行，例如：<code>add = (x, y, z) =&gt; x + y + z→curryAdd = x =&gt; y =&gt; z =&gt; x + y + z；</code></li>
<li>偏函数固定了函数的某个部分，通过传入的参数或者方法返回一个新的函数来接受剩余的参数，数量可能是一个也可能是多个；</li>
<li>当一个柯里化函数只接受两次参数时，比如 <code>curry()()</code>，这时的柯里化函数和偏函数概念类似，可以认为偏函数是柯里化函数的退化版</li>
</ul>
<h2 id="设计原则"><a href="#设计原则" class="headerlink" title="设计原则"></a>设计原则</h2><blockquote>
<p>在前文我们介绍了面向对象三大特性之继承，本文将主要介绍面向对象六大原则中的单一职责原则（SRP）、开放封闭原则（OCP）、最少知识原则（LKP）。</p>
</blockquote>
<blockquote>
<p>设计原则是指导思想，从思想上给我们指明程序设计的正确方向，是我们在开发设计过程中应该尽力遵守的准则。而设计模式是实现手段，因此设计模式也应该遵守这些原则，或者说，设计模式就是这些设计原则的一些具体体现。要达到的目标就是高内聚低耦合，高内聚是说模块内部要高度聚合，是模块内部的关系，低耦合是说模块与模块之间的耦合度要尽量低，是模块与模块间的关系。</p>
</blockquote>
<p><strong>注意</strong>，遵守设计原则是好，但是过犹不及，在实际项目中我们不要刻板遵守，需要根据实际情况灵活运用</p>
<h3 id="1-单一职责原则-SRP"><a href="#1-单一职责原则-SRP" class="headerlink" title="1. 单一职责原则 SRP"></a><strong>1. 单一职责原则 SRP</strong></h3><ul>
<li>单一职责原则 （Single Responsibility Principle, SRP）是指对一个类（方法、对象，下文统称对象）来说，应该仅有一个引起它变化的原因。也就是说，一个对象只做一件事。</li>
<li>单一职责原则可以让我们对对象的维护变得简单，如果一个对象具有多个职责的话，那么如果一个职责的逻辑需要修改，那么势必会影响到其他职责的代码。如果一个对象具有多种职责，职责之间相互耦合，对一个职责的修改会影响到其他职责的实现，这就是属于模块内低内聚高耦合的情况。负责的职责越多，耦合越强，对模块的修改就越来越危险。</li>
</ul>
<p><strong>优点：</strong></p>
<ul>
<li>降低单个类（方法、对象）的复杂度，提高可读性和可维护性，功能之间的界限更清晰； 类（方法、对象）之间根据功能被分为更小的粒度，有助于代码的复用；</li>
<li>缺点： 增加系统中类（方法、对象）的个数，实际上也增加了这些对象之间相互联系的难度，同时也引入了额外的复杂度。</li>
</ul>
<h3 id="2-开放封闭原则-OCP"><a href="#2-开放封闭原则-OCP" class="headerlink" title="2. 开放封闭原则 OCP"></a><strong>2. 开放封闭原则 OCP</strong></h3><blockquote>
<p>开放封闭原则 （Open－Close Principle, OCP）是指一个模块在扩展性方面应该是开放的，而在更改性方面应该是封闭的，也就是对扩展开放，对修改封闭。</p>
</blockquote>
<blockquote>
<p>当需要增加需求的时候，则尽量通过扩展新代码的方式，而不是修改已有代码。因为修改已有代码，则会给依赖原有代码的模块带来隐患，因此修改之后需要把所有依赖原有代码的模块都测试一遍，修改一遍测试一遍，带来的成本很大，如果是上线的大型项目，那么代价和风险可能更高。</p>
</blockquote>
<p><strong>优点</strong>：</p>
<ul>
<li>增加可维护性，避免因为修改给系统带来的不稳定性。</li>
</ul>
<h3 id="3-最少知识原则-LKP"><a href="#3-最少知识原则-LKP" class="headerlink" title="3. 最少知识原则 LKP"></a><strong>3. 最少知识原则 LKP</strong></h3><ul>
<li>最少知识原则 （Least Knowledge Principle, LKP）又称为迪米特原则 （Law of Demeter, LOD），一个对象应该对其他对象有最少的了解。</li>
<li>通俗地讲，一个类应该对自己需要耦合或调用的类知道得最少，类的内部如何实现、如何复杂都与调用者或者依赖者没关系，调用者或者依赖者只需要知道他需要的方法即可，其他的我一概不关心。类与类之间的关系越密切，耦合度越大，当一个类发生改变时，对另一个类的影响也越大。</li>
<li>通常为了减少对象之间的联系，是通过引入一个第三者来帮助进行通信，阻隔对象之间的直接通信，从而减少耦合。</li>
</ul>
<p><strong>优点：</strong></p>
<ul>
<li>降低类（方法、对象）之间不必要的依赖，减少耦合。</li>
</ul>
<p><strong>缺点：</strong></p>
<ul>
<li>类（方法、对象）之间不直接通信也会经过一个第三者来通信，那么就要权衡引入第三者带来的复杂度是否值得。</li>
</ul>
<h1 id="二、创建型模式"><a href="#二、创建型模式" class="headerlink" title="二、创建型模式"></a>二、创建型模式</h1><h2 id="单例模式"><a href="#单例模式" class="headerlink" title="单例模式"></a>单例模式</h2><ul>
<li>单例模式可能是设计模式里面最简单的模式了，虽然简单，但在我们日常生活和编程中却经常接触到，本节我们一起来学习一下。</li>
<li>单例模式 （Singleton Pattern）又称为单体模式，保证一个类只有一个实例，并提供一个访问它的全局访问点。也就是说，第二次使用同一个类创建新对象的时候，应该得到与第一次创建的对象完全相同的对象。</li>
</ul>
<p>经营游戏单例示例代码实现：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">function ManageGame() &#123;</span><br><span class="line">    if (ManageGame._schedule) &#123;        &#x2F;&#x2F; 判断是否已经有单例了</span><br><span class="line">    	return ManageGame._schedule</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F; 没有单例，进行创建</span><br><span class="line">    ManageGame._schedule &#x3D; this</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">ManageGame.getInstance &#x3D; function() &#123;</span><br><span class="line">    if (ManageGame._schedule) &#123;        &#x2F;&#x2F; 判断是否已经有单例了</span><br><span class="line">    	return ManageGame._schedule</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F; 没有单例，进行创建</span><br><span class="line">    return ManageGame._schedule &#x3D; new ManageGame()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">const schedule1 &#x3D; new ManageGame()</span><br><span class="line">const schedule2 &#x3D; ManageGame.getInstance()</span><br><span class="line"></span><br><span class="line">console.log(schedule1 &#x3D;&#x3D;&#x3D; schedule2)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>稍微解释一下，这个构造函数在内部维护（或者直接挂载自己身上）一个实例，第一次执行 new 的时候判断这个实例有没有创建过，创建过就直接返回，否则走创建流程。我们可以用 <code>ES6</code> 的 <code>class</code> 语法改造一下：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ManageGame</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> _schedule = <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="title">getInstance</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="comment">// 判断是否已经有单例了</span></span><br><span class="line">        <span class="keyword">if</span> (ManageGame._schedule) &#123;</span><br><span class="line">            <span class="keyword">return</span> ManageGame._schedule</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 没有单例，进行创建</span></span><br><span class="line">        <span class="keyword">return</span> ManageGame._schedule = <span class="keyword">new</span> ManageGame()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="comment">// 判断是否已经有单例了</span></span><br><span class="line">        <span class="keyword">if</span> (ManageGame._schedule) &#123;</span><br><span class="line">            <span class="keyword">return</span> ManageGame._schedule</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 没有单例，进行创建</span></span><br><span class="line">        ManageGame._schedule = <span class="built_in">this</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> schedule1 = <span class="keyword">new</span> ManageGame()</span><br><span class="line"><span class="keyword">const</span> schedule2 = ManageGame.getInstance()</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(schedule1 === schedule2)	<span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>上面方法的缺点在于维护的实例作为静态属性直接暴露，外部可以直接修改。</p>
<p>可以使用闭包或块状作用域隐藏内部变量：</p>
<p><strong>单例模式赋能</strong></p>
<blockquote>
<p>之前的例子中，单例模式的创建逻辑和原先这个类的一些功能逻辑（比如 <code>init</code> 等操作）混杂在一起，根据单一职责原则，这个例子我们还可以继续改进一下，将单例模式的创建逻辑和特定类的功能逻辑拆开，这样功能逻辑就可以和正常的类一样。</p>
</blockquote>
<p><strong>惰性单例、懒汉式-饿汉式</strong></p>
<ul>
<li>有时候一个实例化过程比较耗费性能的类，但是却一直用不到，如果一开始就对这个类进行实例化就显得有些浪费，那么这时我们就可以使用惰性创建，即延迟创建该类的单例。之前的例子都属于惰性单例，实例的创建都是 <code>new</code> 的时候才进行。</li>
</ul>
<p><strong>单例模式的优缺点</strong></p>
<p>单例模式主要解决的问题就是节约资源，保持访问一致性。</p>
<p><strong>简单分析一下它的优点：</strong></p>
<ul>
<li>单例模式在创建后在内存中只存在一个实例，节约了内存开支和实例化时的性能开支，特别是需要重复使用一个创建开销比较大的类时，比起实例不断地销毁和重新实例化，单例能节约更多资源，比如数据库连接；</li>
<li>单例模式可以解决对资源的多重占用，比如写文件操作时，因为只有一个实例，可以避免对一个文件进行同时操作；</li>
<li>只使用一个实例，也可以减小垃圾回收机制 GC（Garbage Collecation） 的压力，表现在浏览器中就是系统卡顿减少，操作更流畅，CPU 资源占用更少；</li>
</ul>
<p><strong>单例模式也是有缺点的</strong></p>
<ul>
<li>单例模式对扩展不友好，一般不容易扩展，因为单例模式一般自行实例化，没有接口；</li>
<li>与单一职责原则冲突，一个类应该只关心内部逻辑，而不关心外面怎么样来实例化；</li>
</ul>
<p><strong>单例模式的使用场景</strong></p>
<p>那我们应该在什么场景下使用单例模式呢：</p>
<ul>
<li>当一个类的实例化过程消耗的资源过多，可以使用单例模式来避免性能浪费；</li>
<li>当项目中需要一个公共的状态，那么需要使用单例模式来保证访问一致性；</li>
</ul>
<h2 id="工厂模式"><a href="#工厂模式" class="headerlink" title="工厂模式"></a>工厂模式</h2><blockquote>
<p>工厂模式 （Factory Pattern），根据不同的输入返回不同类的实例，一般用来创建同一类对象。工厂方式的主要思想是将对象的创建与对象的实现分离。</p>
</blockquote>
<ul>
<li>访问者只需要知道产品名，就可以从工厂获得对应实例；</li>
<li>访问者不关心实例创建过程；</li>
</ul>
<p><strong>代码实现</strong></p>
<blockquote>
<p>如果你使用过 <code>document.createElement</code> 方法创建过 <code>DOM</code> 元素，那么你已经使用过工厂方法了，虽然这个方法实际上很复杂，但其使用的就是工厂方法的思想：访问者只需提供标签名（如 <code>div</code>、<code>img</code>），那么这个方法就会返回对应的 DOM 元素。</p>
</blockquote>
<p>我们可以使用 JavaScript 将上面饭馆例子实现一下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 饭店方法 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">restaurant</span>(<span class="params">menu</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">switch</span> (menu) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">&#x27;鱼香肉丝&#x27;</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> YuXiangRouSi()</span><br><span class="line">        <span class="keyword">case</span> <span class="string">&#x27;宫保鸡丁&#x27;</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> GongBaoJiDin()</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;这个菜本店没有 -。-&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 鱼香肉丝类 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">YuXiangRouSi</span>(<span class="params"></span>) </span>&#123; <span class="built_in">this</span>.type = <span class="string">&#x27;鱼香肉丝&#x27;</span> &#125;</span><br><span class="line"></span><br><span class="line">YuXiangRouSi.prototype.eat = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.type + <span class="string">&#x27; 真香~&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 宫保鸡丁类 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">GongBaoJiDin</span>(<span class="params"></span>) </span>&#123; <span class="built_in">this</span>.type = <span class="string">&#x27;宫保鸡丁&#x27;</span> &#125;</span><br><span class="line"></span><br><span class="line">GongBaoJiDin.prototype.eat = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.type + <span class="string">&#x27; 让我想起了外婆做的菜~&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> dish1 = restaurant(<span class="string">&#x27;鱼香肉丝&#x27;</span>)</span><br><span class="line">dish1.eat()													<span class="comment">// 输出: 鱼香肉丝 真香~</span></span><br><span class="line"><span class="keyword">const</span> dish2 = restaurant(<span class="string">&#x27;红烧排骨&#x27;</span>) <span class="comment">// 输出: Error 这个菜本店没有 -。-</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>工厂方法中这里使用 <code>switch-case</code> 语法，你也可以用 <code>if-else</code>，都可以。</p>
</blockquote>
<p>下面使用 ES6 的 class 语法改写一下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 饭店方法 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Restaurant</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="title">getMenu</span>(<span class="params">menu</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">switch</span> (menu) &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;鱼香肉丝&#x27;</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> YuXiangRouSi()</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;宫保鸡丁&#x27;</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> GongBaoJiDin()</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;这个菜本店没有 -。-&#x27;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 鱼香肉丝类 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">YuXiangRouSi</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123; <span class="built_in">this</span>.type = <span class="string">&#x27;鱼香肉丝&#x27;</span> &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">eat</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="built_in">this</span>.type + <span class="string">&#x27; 真香~&#x27;</span>) &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 宫保鸡丁类 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GongBaoJiDin</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123; <span class="built_in">this</span>.type = <span class="string">&#x27;宫保鸡丁&#x27;</span> &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">eat</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="built_in">this</span>.type + <span class="string">&#x27; 让我想起了外婆做的菜~&#x27;</span>) &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> dish1 = Restaurant.getMenu(<span class="string">&#x27;鱼香肉丝&#x27;</span>)</span><br><span class="line"><span class="comment">// 输出: 鱼香肉丝 真香~</span></span><br><span class="line">dish1.eat()</span><br><span class="line"><span class="keyword">const</span> dish2 = Restaurant.getMenu(<span class="string">&#x27;红烧排骨&#x27;</span>)	<span class="comment">// 输出: Error 这个菜本店没有 -。-</span></span><br></pre></td></tr></table></figure>

<ul>
<li>这样就完成了一个工厂模式，但是这个实现有一个问题：工厂方法中包含了很多与创建产品相关的过程，如果产品种类很多的话，这个工厂方法中就会罗列很多产品的创建逻辑，每次新增或删除产品种类，不仅要增加产品类，还需要对应修改在工厂方法，违反了开闭原则，也导致这个工厂方法变得臃肿、高耦合。</li>
<li>严格上这种实现在面向对象语言中叫做简单工厂模式。适用于产品种类比较少，创建逻辑不复杂的时候使用。</li>
<li>工厂模式的本意是将实际创建对象的过程推迟到子类中，一般用抽象类来作为父类，创建过程由抽象类的子类来具体实现。JavaScript 中没有抽象类，所以我们可以简单地将工厂模式看做是一个实例化对象的工厂类即可。关于抽象类的有关内容，可以参看抽象工厂模式。</li>
<li>然而作为灵活的 JavaScript，我们不必如此较真，可以把易变的参数提取出来：</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 饭店方法 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Restaurant</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.menuData = &#123;&#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 创建菜品 */</span></span><br><span class="line">    <span class="function"><span class="title">getMenu</span>(<span class="params">menu</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (!<span class="built_in">this</span>.menuData[menu])</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;这个菜本店没有 -。-&#x27;</span>)</span><br><span class="line">        <span class="keyword">const</span> &#123; type, message &#125; = <span class="built_in">this</span>.menuData[menu]</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Menu(type, message)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 增加菜品种类 */</span></span><br><span class="line">    <span class="function"><span class="title">addMenu</span>(<span class="params">menu, type, message</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">this</span>.menuData[menu]) &#123;</span><br><span class="line">            <span class="built_in">console</span>.Info(<span class="string">&#x27;已经有这个菜了!&#x27;</span>)</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">this</span>.menuData[menu] = &#123; type, message &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 移除菜品 */</span></span><br><span class="line">    <span class="function"><span class="title">removeMenu</span>(<span class="params">menu</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (!<span class="built_in">this</span>.menuData[menu]) <span class="keyword">return</span></span><br><span class="line">        <span class="keyword">delete</span> <span class="built_in">this</span>.menuData[menu]</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 菜品类 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Menu</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">type, message</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.type = type</span><br><span class="line">        <span class="built_in">this</span>.message = message</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">eat</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="built_in">this</span>.type + <span class="built_in">this</span>.message) &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> restaurant = <span class="keyword">new</span> Restaurant()</span><br><span class="line">restaurant.addMenu(<span class="string">&#x27;YuXiangRouSi&#x27;</span>, <span class="string">&#x27;鱼香肉丝&#x27;</span>, <span class="string">&#x27; 真香~&#x27;</span>)			<span class="comment">// 注册菜品</span></span><br><span class="line">restaurant.addMenu(<span class="string">&#x27;GongBaoJiDin&#x27;</span>, <span class="string">&#x27;宫保鸡丁&#x27;</span>, <span class="string">&#x27; 让我想起了外婆做的菜~&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> dish1 = restaurant.getMenu(<span class="string">&#x27;YuXiangRouSi&#x27;</span>)</span><br><span class="line">dish1.eat()																				<span class="comment">// 输出: 鱼香肉丝 真香~</span></span><br><span class="line"><span class="keyword">const</span> dish2 = restaurant.getMenu(<span class="string">&#x27;HongSaoPaiGu&#x27;</span>)	<span class="comment">// 输出: Error 这个菜本店没有 -。-</span></span><br></pre></td></tr></table></figure>

<ul>
<li>我们还给 Restaurant 类增加了 <code>addMenu/removeMenu</code> 私有方法，以便于扩展。</li>
<li>当然这里如果菜品参数不太一致，可以在 <code>addMenu</code> 时候注册构造函数或者类，创建的时候返回 <code>new</code> 出的对应类实例，灵活变通即可。</li>
</ul>
<p> <strong>工厂模式的优缺点</strong></p>
<p>工厂模式将对象的创建和实现分离，这带来了优点：</p>
<ul>
<li>良好的封装，代码结构清晰，访问者无需知道对象的创建流程，特别是创建比较复杂的情况下；</li>
<li>扩展性优良，通过工厂方法隔离了用户和创建流程隔离，符合开放封闭原则；</li>
<li>解耦了高层逻辑和底层产品类，符合最少知识原则，不需要的就不要去交流；</li>
<li>工厂模式的缺点：带来了额外的系统复杂度，增加了抽象性；</li>
</ul>
<p><strong>工厂模式的使用场景</strong></p>
<p>那么什么时候使用工厂模式呢：</p>
<ul>
<li>对象的创建比较复杂，而访问者无需知道创建的具体流程；</li>
<li>处理大量具有相同属性的小对象；</li>
</ul>
<h2 id="抽象工厂模式"><a href="#抽象工厂模式" class="headerlink" title="抽象工厂模式"></a>抽象工厂模式</h2><blockquote>
<p>工厂模式 （Factory Pattern），根据输入的不同返回不同类的实例，一般用来创建同一类对象。工厂方式的主要思想是将对象的创建与对象的实现分离。</p>
</blockquote>
<ul>
<li>抽象工厂 （Abstract Factory）：通过对类的工厂抽象使其业务用于对产品类簇的创建，而不是负责创建某一类产品的实例。关键在于使用抽象类制定了实例的结构，调用者直接面向实例的结构编程，从实例的具体实现中解耦。</li>
<li>我们知道 JavaScript 并不是强面向对象语言，所以使用传统编译型语言比如 JAVA、C#、C++ 等实现的设计模式和 JavaScript 不太一样，比如 JavaScript 中没有原生的类和接口等（不过 ES6+ 渐渐提供类似的语法糖），我们可以用变通的方式来解决。最重要的是设计模式背后的核心思想，和它所要解决的问题。</li>
</ul>
<p><strong>代码实现</strong></p>
<blockquote>
<p>我们知道 JavaScript 并不强面向对象，也没有提供抽象类（至少目前没有提供），但是可以模拟抽象类。用对 <code>new.target</code> 来判断 new 的类，在父类方法中 <code>throw new Error()</code>，如果子类中没有实现这个方法就会抛错，这样来模拟抽象类：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 抽象类，ES6 class 方式 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AbstractClass1</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">new</span>.target === AbstractClass1) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;抽象类不能直接实例化!&#x27;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 抽象方法 */</span></span><br><span class="line">    <span class="function"><span class="title">operate</span>(<span class="params"></span>)</span> &#123; <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;抽象方法不能调用!&#x27;</span>) &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 抽象类，ES5 构造函数方式 */</span></span><br><span class="line"><span class="keyword">var</span> AbstractClass2 = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">new</span>.target === AbstractClass2) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;抽象类不能直接实例化!&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* 抽象方法，使用原型方式添加 */</span></span><br><span class="line">AbstractClass2.prototype.operate = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;抽象方法不能调用!&#x27;</span>) &#125;</span><br></pre></td></tr></table></figure>

<p>下面用 JavaScript 将上面介绍的饭店例子实现一下。</p>
<p>首先使用原型方式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 饭店方法 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Restaurant</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">Restaurant.orderDish = <span class="function"><span class="keyword">function</span>(<span class="params">type</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">switch</span> (type) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">&#x27;鱼香肉丝&#x27;</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> YuXiangRouSi()</span><br><span class="line">        <span class="keyword">case</span> <span class="string">&#x27;宫保鸡丁&#x27;</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> GongBaoJiDing()</span><br><span class="line">        <span class="keyword">case</span> <span class="string">&#x27;紫菜蛋汤&#x27;</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ZiCaiDanTang()</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;本店没有这个 -。-&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 菜品抽象类 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Dish</span>(<span class="params"></span>) </span>&#123; <span class="built_in">this</span>.kind = <span class="string">&#x27;菜&#x27;</span> &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 抽象方法 */</span></span><br><span class="line">Dish.prototype.eat = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;抽象方法不能调用!&#x27;</span>) &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 鱼香肉丝类 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">YuXiangRouSi</span>(<span class="params"></span>) </span>&#123; <span class="built_in">this</span>.type = <span class="string">&#x27;鱼香肉丝&#x27;</span> &#125;</span><br><span class="line"></span><br><span class="line">YuXiangRouSi.prototype = <span class="keyword">new</span> Dish()</span><br><span class="line"></span><br><span class="line">YuXiangRouSi.prototype.eat = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.kind + <span class="string">&#x27; - &#x27;</span> + <span class="built_in">this</span>.type + <span class="string">&#x27; 真香~&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 宫保鸡丁类 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">GongBaoJiDing</span>(<span class="params"></span>) </span>&#123; <span class="built_in">this</span>.type = <span class="string">&#x27;宫保鸡丁&#x27;</span> &#125;</span><br><span class="line"></span><br><span class="line">GongBaoJiDing.prototype = <span class="keyword">new</span> Dish()</span><br><span class="line"></span><br><span class="line">GongBaoJiDing.prototype.eat = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.kind + <span class="string">&#x27; - &#x27;</span> + <span class="built_in">this</span>.type + <span class="string">&#x27; 让我想起了外婆做的菜~&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> dish1 = Restaurant.orderDish(<span class="string">&#x27;鱼香肉丝&#x27;</span>)</span><br><span class="line">dish1.eat()</span><br><span class="line"><span class="keyword">const</span> dish2 = Restaurant.orderDish(<span class="string">&#x27;红烧排骨&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出: 菜 - 鱼香肉丝 真香~</span></span><br><span class="line"><span class="comment">// 输出: Error 本店没有这个 -。-</span></span><br><span class="line">使用 <span class="class"><span class="keyword">class</span> 语法改写一下：</span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class">/* 饭店方法 */</span></span><br><span class="line"><span class="class"><span class="title">class</span> <span class="title">Restaurant</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="title">orderDish</span>(<span class="params">type</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">switch</span> (type) &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;鱼香肉丝&#x27;</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> YuXiangRouSi()</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;宫保鸡丁&#x27;</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> GongBaoJiDin()</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;本店没有这个 -。-&#x27;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 菜品抽象类 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dish</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">new</span>.target === Dish) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;抽象类不能直接实例化!&#x27;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">this</span>.kind = <span class="string">&#x27;菜&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/* 抽象方法 */</span></span><br><span class="line">    <span class="function"><span class="title">eat</span>(<span class="params"></span>)</span> &#123; <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;抽象方法不能调用!&#x27;</span>) &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 鱼香肉丝类 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">YuXiangRouSi</span> <span class="keyword">extends</span> <span class="title">Dish</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>()</span><br><span class="line">        <span class="built_in">this</span>.type = <span class="string">&#x27;鱼香肉丝&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">eat</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="built_in">this</span>.kind + <span class="string">&#x27; - &#x27;</span> + <span class="built_in">this</span>.type + <span class="string">&#x27; 真香~&#x27;</span>) &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 宫保鸡丁类 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GongBaoJiDin</span> <span class="keyword">extends</span> <span class="title">Dish</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>()</span><br><span class="line">        <span class="built_in">this</span>.type = <span class="string">&#x27;宫保鸡丁&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">eat</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="built_in">this</span>.kind + <span class="string">&#x27; - &#x27;</span> + <span class="built_in">this</span>.type + <span class="string">&#x27; 让我想起了外婆做的菜~&#x27;</span>) &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> dish0 = <span class="keyword">new</span> Dish()  										<span class="comment">// 输出: Error 抽象方法不能调用!</span></span><br><span class="line"><span class="keyword">const</span> dish1 = Restaurant.orderDish(<span class="string">&#x27;鱼香肉丝&#x27;</span>)</span><br><span class="line">dish1.eat()																		<span class="comment">// 输出: 菜 - 鱼香肉丝 真香~</span></span><br><span class="line"><span class="keyword">const</span> dish2 = Restaurant.orderDish(<span class="string">&#x27;红烧排骨&#x27;</span>) <span class="comment">// 输出: Error 本店没有这个 -。-</span></span><br></pre></td></tr></table></figure>

<p><strong>抽象工厂模式的优缺点</strong></p>
<p><strong>抽象模式的优点：</strong></p>
<blockquote>
<p>抽象产品类将产品的结构抽象出来，访问者不需要知道产品的具体实现，只需要面向产品的结构编程即可，从产品的具体实现中解耦；</p>
</blockquote>
<p><strong>抽象模式的缺点：</strong></p>
<ul>
<li>扩展新类簇的产品类比较困难，因为需要创建新的抽象产品类，并且还要修改工厂类，违反开闭原则；</li>
<li>带来了系统复杂度，增加了新的类，和新的继承关系；</li>
</ul>
<p><strong>抽象工厂模式的使用场景</strong></p>
<blockquote>
<p>如果一组实例都有相同的结构，那么就可以使用抽象工厂模式。</p>
</blockquote>
<p> <strong>抽象工厂模式与工厂模式</strong></p>
<p>工厂模式和抽象工厂模式的区别：</p>
<ul>
<li>工厂模式 主要关注单独的产品实例的创建；</li>
<li>抽象工厂模式 主要关注产品类簇实例的创建，如果产品类簇只有一个产品，那么这时的抽象工厂模式就退化为工厂模式了；根据场景灵活使用即可。</li>
</ul>
<h2 id="建造者模式"><a href="#建造者模式" class="headerlink" title="建造者模式"></a>建造者模式</h2><blockquote>
<p>建造者模式（Builder Pattern）又称生成器模式，分步构建一个复杂对象，并允许按步骤构造。同样的构建过程可以采用不同的表示，将一个复杂对象的构建层与其表示层分离。</p>
</blockquote>
<ul>
<li>在工厂模式中，创建的结果都是一个完整的个体，我们对创建的过程并不关心，只需了解创建的结果。而在建造者模式中，我们关心的是对象的创建过程，因此我们通常将创建的复杂对象的模块化，使得被创建的对象的每一个子模块都可以得到高质量的复用，当然在灵活的 JavaScript 中我们可以有更灵活的实现。</li>
</ul>
<p>汽车装配代码模式</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 建造者，汽车部件厂家，提供具体零部件的生产</span><br><span class="line">function CarBuilder(&#123; color &#x3D; &#39;white&#39;, weight &#x3D; 0 &#125;) &#123;</span><br><span class="line">    this.color &#x3D; color</span><br><span class="line">    this.weight &#x3D; weight</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 生产部件，轮胎</span><br><span class="line">CarBuilder.prototype.buildTyre &#x3D; function(type) &#123;</span><br><span class="line">    switch (type) &#123;</span><br><span class="line">        case &#39;small&#39;:</span><br><span class="line">            this.tyreType &#x3D; &#39;小号轮胎&#39;</span><br><span class="line">            this.tyreIntro &#x3D; &#39;正在使用小号轮胎&#39;</span><br><span class="line">            break</span><br><span class="line">        case &#39;normal&#39;:</span><br><span class="line">            this.tyreType &#x3D; &#39;中号轮胎&#39;</span><br><span class="line">            this.tyreIntro &#x3D; &#39;正在使用中号轮胎&#39;</span><br><span class="line">            break</span><br><span class="line">        case &#39;big&#39;:</span><br><span class="line">            this.tyreType &#x3D; &#39;大号轮胎&#39;</span><br><span class="line">            this.tyreIntro &#x3D; &#39;正在使用大号轮胎&#39;</span><br><span class="line">            break</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 生产部件，发动机</span><br><span class="line">CarBuilder.prototype.buildEngine &#x3D; function(type) &#123;</span><br><span class="line">    switch (type) &#123;</span><br><span class="line">        case &#39;small&#39;:</span><br><span class="line">            this.engineType &#x3D; &#39;小马力发动机&#39;</span><br><span class="line">            this.engineIntro &#x3D; &#39;正在使用小马力发动机&#39;</span><br><span class="line">            break</span><br><span class="line">        case &#39;normal&#39;:</span><br><span class="line">            this.engineType &#x3D; &#39;中马力发动机&#39;</span><br><span class="line">            this.engineIntro &#x3D; &#39;正在使用中马力发动机&#39;</span><br><span class="line">            break</span><br><span class="line">        case &#39;big&#39;:</span><br><span class="line">            this.engineType &#x3D; &#39;大马力发动机&#39;</span><br><span class="line">            this.engineIntro &#x3D; &#39;正在使用大马力发动机&#39;</span><br><span class="line">            break</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;* 奔驰厂家，负责最终汽车产品的装配 *&#x2F;</span><br><span class="line">function benChiDirector(tyre, engine, param) &#123;</span><br><span class="line">    var _car &#x3D; new CarBuilder(param)</span><br><span class="line">    _car.buildTyre(tyre)</span><br><span class="line">    _car.buildEngine(engine)</span><br><span class="line">    return _car</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 获得产品实例</span><br><span class="line">var benchi1 &#x3D; benChiDirector(&#39;small&#39;, &#39;big&#39;, &#123; color: &#39;red&#39;, weight: &#39;1600kg&#39; &#125;)</span><br><span class="line"></span><br><span class="line">console.log(benchi1)</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 输出：</span><br><span class="line">&#x2F;&#x2F; &#123;</span><br><span class="line">&#x2F;&#x2F;   color: &quot;red&quot;</span><br><span class="line">&#x2F;&#x2F;   weight: &quot;1600kg&quot;</span><br><span class="line">&#x2F;&#x2F;   tyre: Tyre &#123;tyreType: &quot;小号轮胎&quot;, tyreIntro: &quot;正在使用小号轮胎&quot;&#125;</span><br><span class="line">&#x2F;&#x2F;   engine: Engine &#123;engineType: &quot;大马力发动机&quot;, engineIntro: &quot;正在使用大马力发动机&quot;&#125;</span><br><span class="line">&#x2F;&#x2F; &#125;</span><br></pre></td></tr></table></figure>

<p>ES6写法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 建造者，汽车部件厂家，提供具体零部件的生产</span><br><span class="line">class CarBuilder &#123;</span><br><span class="line">    constructor(&#123; color &#x3D; &#39;white&#39;, weight &#x3D; 0 &#125;) &#123;</span><br><span class="line">        this.color &#x3D; color</span><br><span class="line">        this.weight &#x3D; weight</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    &#x2F;* 生产部件，轮胎 *&#x2F;</span><br><span class="line">    buildTyre(type) &#123;</span><br><span class="line">        const tyre &#x3D; &#123;&#125;</span><br><span class="line">        switch (type) &#123;</span><br><span class="line">            case &#39;small&#39;:</span><br><span class="line">                tyre.tyreType &#x3D; &#39;小号轮胎&#39;</span><br><span class="line">                tyre.tyreIntro &#x3D; &#39;正在使用小号轮胎&#39;</span><br><span class="line">                break</span><br><span class="line">            case &#39;normal&#39;:</span><br><span class="line">                tyre.tyreType &#x3D; &#39;中号轮胎&#39;</span><br><span class="line">                tyre.tyreIntro &#x3D; &#39;正在使用中号轮胎&#39;</span><br><span class="line">                break</span><br><span class="line">            case &#39;big&#39;:</span><br><span class="line">                tyre.tyreType &#x3D; &#39;大号轮胎&#39;</span><br><span class="line">                tyre.tyreIntro &#x3D; &#39;正在使用大号轮胎&#39;</span><br><span class="line">                break</span><br><span class="line">        &#125;</span><br><span class="line">        this.tyre &#x3D; tyre</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    &#x2F;* 生产部件，发动机 *&#x2F;</span><br><span class="line">    buildEngine(type) &#123;</span><br><span class="line">        const engine &#x3D; &#123;&#125;</span><br><span class="line">        switch (type) &#123;</span><br><span class="line">            case &#39;small&#39;:</span><br><span class="line">                engine.engineType &#x3D; &#39;小马力发动机&#39;</span><br><span class="line">                engine.engineIntro &#x3D; &#39;正在使用小马力发动机&#39;</span><br><span class="line">                break</span><br><span class="line">            case &#39;normal&#39;:</span><br><span class="line">                engine.engineType &#x3D; &#39;中马力发动机&#39;</span><br><span class="line">                engine.engineIntro &#x3D; &#39;正在使用中马力发动机&#39;</span><br><span class="line">                break</span><br><span class="line">            case &#39;big&#39;:</span><br><span class="line">                engine.engineType &#x3D; &#39;大马力发动机&#39;</span><br><span class="line">                engine.engineIntro &#x3D; &#39;正在使用大马力发动机&#39;</span><br><span class="line">                break</span><br><span class="line">        &#125;</span><br><span class="line">        this.engine &#x3D; engine</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;* 指挥者，负责最终汽车产品的装配 *&#x2F;</span><br><span class="line">class BenChiDirector &#123;</span><br><span class="line">    constructor(tyre, engine, param) &#123;</span><br><span class="line">        const _car &#x3D; new CarBuilder(param)</span><br><span class="line">        _car.buildTyre(tyre)</span><br><span class="line">        _car.buildEngine(engine)</span><br><span class="line">        return _car</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 获得产品实例</span><br><span class="line">const benchi1 &#x3D; new BenChiDirector(&#39;small&#39;, &#39;big&#39;, &#123; color: &#39;red&#39;, weight: &#39;1600kg&#39; &#125;)</span><br><span class="line"></span><br><span class="line">console.log(benchi1)</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 输出：</span><br><span class="line">&#x2F;&#x2F; &#123;</span><br><span class="line">&#x2F;&#x2F;   color: &quot;red&quot;</span><br><span class="line">&#x2F;&#x2F;   weight: &quot;1600kg&quot;</span><br><span class="line">&#x2F;&#x2F;   tyre: Tyre &#123;tyreType: &quot;小号轮胎&quot;, tyreIntro: &quot;正在使用小号轮胎&quot;&#125;</span><br><span class="line">&#x2F;&#x2F;   engine: Engine &#123;engineType: &quot;大马力发动机&quot;, engineIntro: &quot;正在使用大马力发动机&quot;&#125;</span><br><span class="line">&#x2F;&#x2F; &#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>作为灵活的 JavaScript，我们还可以使用链模式来完成部件的装配</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 建造者，汽车部件厂家</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CarBuilder</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">&#123; color = <span class="string">&#x27;white&#x27;</span>, weight = <span class="string">&#x27;0&#x27;</span> &#125;</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.color = color</span><br><span class="line">        <span class="built_in">this</span>.weight = weight</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/* 生产部件，轮胎 */</span></span><br><span class="line">    <span class="function"><span class="title">buildTyre</span>(<span class="params">type</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> tyre = &#123;&#125;</span><br><span class="line">        <span class="keyword">switch</span> (type) &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;small&#x27;</span>:</span><br><span class="line">                tyre.tyreType = <span class="string">&#x27;小号轮胎&#x27;</span></span><br><span class="line">                tyre.tyreIntro = <span class="string">&#x27;正在使用小号轮胎&#x27;</span></span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;normal&#x27;</span>:</span><br><span class="line">                tyre.tyreType = <span class="string">&#x27;中号轮胎&#x27;</span></span><br><span class="line">                tyre.tyreIntro = <span class="string">&#x27;正在使用中号轮胎&#x27;</span></span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;big&#x27;</span>:</span><br><span class="line">                tyre.tyreType = <span class="string">&#x27;大号轮胎&#x27;</span></span><br><span class="line">                tyre.tyreIntro = <span class="string">&#x27;正在使用大号轮胎&#x27;</span></span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">this</span>.tyre = tyre</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/* 生产部件，发动机 */</span></span><br><span class="line">    <span class="function"><span class="title">buildEngine</span>(<span class="params">type</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> engine = &#123;&#125;</span><br><span class="line">        <span class="keyword">switch</span> (type) &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;small&#x27;</span>:</span><br><span class="line">                engine.engineType = <span class="string">&#x27;小马力发动机&#x27;</span></span><br><span class="line">                engine.engineIntro = <span class="string">&#x27;正在使用小马力发动机&#x27;</span></span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;normal&#x27;</span>:</span><br><span class="line">                engine.engineType = <span class="string">&#x27;中马力发动机&#x27;</span></span><br><span class="line">                engine.engineIntro = <span class="string">&#x27;正在使用中马力发动机&#x27;</span></span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            <span class="keyword">case</span> <span class="string">&#x27;big&#x27;</span>:</span><br><span class="line">                engine.engineType = <span class="string">&#x27;大马力发动机&#x27;</span></span><br><span class="line">                engine.engineIntro = <span class="string">&#x27;正在使用大马力发动机&#x27;</span></span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">this</span>.engine = engine</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 汽车装配，获得产品实例</span></span><br><span class="line"><span class="keyword">const</span> benchi1 = <span class="keyword">new</span> CarBuilder(&#123; <span class="attr">color</span>: <span class="string">&#x27;red&#x27;</span>, <span class="attr">weight</span>: <span class="string">&#x27;1600kg&#x27;</span> &#125;)</span><br><span class="line">    .buildTyre(<span class="string">&#x27;small&#x27;</span>)</span><br><span class="line">    .buildEngine(<span class="string">&#x27;big&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(benchi1)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出：</span></span><br><span class="line"><span class="comment">// &#123;</span></span><br><span class="line"><span class="comment">//   color: &quot;red&quot;</span></span><br><span class="line"><span class="comment">//   weight: &quot;1600kg&quot;</span></span><br><span class="line"><span class="comment">//   tyre: Tyre &#123;tyre: &quot;小号轮胎&quot;, tyreIntro: &quot;正在使用小号轮胎&quot;&#125;</span></span><br><span class="line"><span class="comment">//   engine: Engine &#123;engine: &quot;大马力发动机&quot;, engineIntro: &quot;正在使用大马力发动机&quot;&#125;</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>这样将最终产品的创建流程使用链模式来实现，相当于将指挥者退化，指挥的过程通过链模式让用户自己实现，这样既增加了灵活性，装配过程也一目了然。如果希望扩展产品的部件，那么在建造者上增加部件实现方法，再适当修改链模式即可。</p>
</blockquote>
<p><strong>建造者模式的优点：</strong></p>
<ul>
<li>使用建造者模式可以使产品的构建流程和产品的表现分离，也就是将产品的创建算法和产品组成的实现隔离，访问者不必知道产品部件实现的细节；</li>
<li>扩展方便，如果希望生产一个装配顺序或方式不同的新产品，那么直接新建一个指挥者即可，不用修改既有代码，符合开闭原则；</li>
<li>更好的复用性，建造者模式将产品的创建算法和产品组成的实现分离，所以产品创建的算法可以复用，产品部件的实现也可以复用，带来很大的灵活性；</li>
</ul>
<p><strong>建造者模式的缺点：</strong></p>
<ul>
<li>建造者模式一般适用于产品之间组成部件类似的情况，如果产品之间差异性很大、复用性不高，那么不要使用建造者模式；</li>
<li>实例的创建增加了许多额外的结构，无疑增加了许多复杂度，如果对象粒度不大，那么我们最好直接创建对象；</li>
</ul>
<p> <strong>建造者模式的适用场景</strong></p>
<ul>
<li>相同的方法，不同的执行顺序，产生不一样的产品时，可以采用建造者模式；</li>
<li>产品的组成部件类似，通过组装不同的组件获得不同产品时，可以采用建造者模式；</li>
</ul>
<p><strong>建造者模式与工厂模式</strong></p>
<ul>
<li>建造者模式和工厂模式最终都是创建一个完整的产品，但是在建造者模式中我们更关心对象创建的过程，将创建对象的方法模块化，从而更好地复用这些模块。</li>
<li>当然建造者模式与工厂模式也是可以组合使用的，比如建造者中一般会提供不同的部件实现，那么这里就可以使用工厂模式来提供具体的部件对象，再通过指挥者来进行装配。</li>
</ul>
<p>** 建造者模式与模版方法模式**</p>
<ul>
<li>指挥者的实现可以和模版方法模式相结合。也就是说，指挥者中部件的装配过程，可以使用模版方法模式来固定装配算法，把部件实现方法分为模板方法和基本方法，进一步提取公共代码，扩展可变部分。</li>
<li>是否采用模版方法模式看具体场景，如果产品的部件装配顺序很明确，但是具体的实现是未知的、灵活的，那么你可以适当考虑是否应该将算法骨架提取出来。</li>
</ul>
<h1 id="三、结构型模式"><a href="#三、结构型模式" class="headerlink" title="三、结构型模式"></a><strong>三、结构型模式</strong></h1><h2 id="代理模式"><a href="#代理模式" class="headerlink" title="代理模式"></a>代理模式</h2><blockquote>
<p>代理模式 （Proxy Pattern）又称委托模式，它为目标对象创造了一个代理对象，以控制对目标对象的访问。</p>
</blockquote>
<ul>
<li>代理模式把代理对象插入到访问者和目标对象之间，从而为访问者对目标对象的访问引入一定的间接性。正是这种间接性，给了代理对象很多操作空间，比如在调用目标对象前和调用后进行一些预操作和后操作，从而实现新的功能或者扩展目标的功能。</li>
</ul>
<p><strong>实例的代码实现</strong></p>
<p>我们使用 JavaScript 来将上面的明星例子实现一下。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 明星 */</span></span><br><span class="line"><span class="keyword">var</span> SuperStar = &#123;</span><br><span class="line">    name: <span class="string">&#x27;小鲜肉&#x27;</span>,</span><br><span class="line">    playAdvertisement: <span class="function"><span class="keyword">function</span>(<span class="params">ad</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(ad)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 经纪人 */</span></span><br><span class="line"><span class="keyword">var</span> ProxyAssistant = &#123;</span><br><span class="line">    name: <span class="string">&#x27;经纪人张某&#x27;</span>,</span><br><span class="line">    playAdvertisement: <span class="function"><span class="keyword">function</span>(<span class="params">reward, ad</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (reward &gt; <span class="number">1000000</span>) &#123;             <span class="comment">// 如果报酬超过100w</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;没问题，我们小鲜鲜最喜欢拍广告了！&#x27;</span>)</span><br><span class="line">            SuperStar.playAdvertisement(ad)</span><br><span class="line">        &#125; <span class="keyword">else</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;没空，滚！&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">ProxyAssistant.playAdvertisement(<span class="number">10000</span>, <span class="string">&#x27;纯蒸酸牛奶，味道纯纯，尽享纯蒸&#x27;</span>)</span><br><span class="line"><span class="comment">// 输出： 没空，滚</span></span><br></pre></td></tr></table></figure>

<ul>
<li>我们可以升级一下，比如如果明星没有档期的话，可以通过经纪人安排档期，当明星有空的时候才让明星来拍广告。这里通过 <code>Promise</code> 的方式来实现档期的安排：</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 明星 */</span></span><br><span class="line"><span class="keyword">const</span> SuperStar = &#123;</span><br><span class="line">    name: <span class="string">&#x27;小鲜肉&#x27;</span>,</span><br><span class="line">    <span class="function"><span class="title">playAdvertisement</span>(<span class="params">ad</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(ad)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 经纪人 */</span></span><br><span class="line"><span class="keyword">const</span> ProxyAssistant = &#123;</span><br><span class="line">    name: <span class="string">&#x27;经纪人张某&#x27;</span>,</span><br><span class="line">    <span class="function"><span class="title">scheduleTime</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">&#x27;小鲜鲜有空了&#x27;</span>)</span><br><span class="line">                resolve()</span><br><span class="line">            &#125;, <span class="number">2000</span>)                        <span class="comment">// 发现明星有空了</span></span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="function"><span class="title">playAdvertisement</span>(<span class="params">reward, ad</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (reward &gt; <span class="number">1000000</span>) &#123;             <span class="comment">// 如果报酬超过100w</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;没问题，我们小鲜鲜最喜欢拍广告了！&#x27;</span>)</span><br><span class="line">            ProxyAssistant.scheduleTime()   <span class="comment">// 安排上了</span></span><br><span class="line">                .then(<span class="function">() =&gt;</span> SuperStar.playAdvertisement(ad))</span><br><span class="line">        &#125; <span class="keyword">else</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;没空，滚！&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">ProxyAssistant.playAdvertisement(<span class="number">10000</span>, <span class="string">&#x27;纯蒸酸牛奶，味道纯纯，尽享纯蒸&#x27;</span>)</span><br><span class="line"><span class="comment">// 输出： 没空，滚</span></span><br><span class="line"></span><br><span class="line">ProxyAssistant.playAdvertisement(<span class="number">1000001</span>, <span class="string">&#x27;纯蒸酸牛奶，味道纯纯，尽享纯蒸&#x27;</span>)</span><br><span class="line"><span class="comment">// 输出： 没问题，我们小鲜鲜最喜欢拍广告了！</span></span><br><span class="line"><span class="comment">// 2秒后</span></span><br><span class="line"><span class="comment">// 输出： 小鲜鲜有空了</span></span><br><span class="line"><span class="comment">// 输出： 纯蒸酸牛奶，味道纯纯，尽享纯蒸</span></span><br></pre></td></tr></table></figure>

<p>这里就简单实现了经纪人对请求的过滤，对明星档期的安排，实现了一个代理对象的基本功能。</p>
<p><strong>代理模式的优缺点</strong></p>
<p><strong>代理模式的主要优点有：</strong></p>
<ul>
<li>代理对象在访问者与目标对象之间可以起到中介和保护目标对象的作用；</li>
<li>代理对象可以扩展目标对象的功能；</li>
<li>代理模式能将访问者与目标对象分离，在一定程度上降低了系统的耦合度，如果我们希望适度扩展目标对象的一些功能，通过修改代理对象就可以了，符合开闭原则；</li>
<li>代理模式的缺点主要是增加了系统的复杂度，要斟酌当前场景是不是真的需要引入代理模式（十八线明星就别请经纪人了）</li>
</ul>
<p><strong>其他相关模式</strong></p>
<p>很多其他的模式，比如状态模式、策略模式、访问者模式其实也是使用了代理模式，包括在之前高阶函数处介绍的备忘模式，本质上也是一种缓存代理。</p>
<p><strong>代理模式与适配器模式</strong></p>
<p>代理模式和适配器模式都为另一个对象提供间接性的访问，他们的区别：</p>
<ul>
<li>适配器模式： 主要用来解决接口之间不匹配的问题，通常是为所适配的对象提供一个不同的接口；</li>
<li>代理模式： 提供访问目标对象的间接访问，以及对目标对象功能的扩展，一般提供和目标对象一样的接口；</li>
</ul>
<p><strong>代理模式与装饰者模式</strong></p>
<p>装饰者模式实现上和代理模式类似，都是在访问目标对象之前或者之后执行一些逻辑，但是目的和功能不同：</p>
<ul>
<li>装饰者模式： 目的是为了方便地给目标对象添加功能，也就是动态地添加功能；</li>
<li>代理模式： 主要目的是控制其他访问者对目标对象的访问；</li>
</ul>
<h2 id="享元模式"><a href="#享元模式" class="headerlink" title="享元模式"></a>享元模式</h2><blockquote>
<p>享元模式 （Flyweight Pattern）运用共享技术来有效地支持大量细粒度对象的复用，以减少创建的对象的数量。</p>
</blockquote>
<blockquote>
<p>享元模式的主要思想是共享细粒度对象，也就是说如果系统中存在多个相同的对象，那么只需共享一份就可以了，不必每个都去实例化每一个对象，这样来精简内存资源，提升性能和效率。</p>
</blockquote>
<p>Fly 意为苍蝇，Flyweight 指轻蝇量级，指代对象粒度很小。</p>
<p><strong>代码实现</strong></p>
<p>首先假设考生的 ID 为奇数则考的是手动档，为偶数则考的是自动档。如果给所有考生都 new 一个驾考车，那么这个系统中就会创建了和考生数量一致的驾考车对象：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> candidateNum = <span class="number">10</span>   <span class="comment">// 考生数量</span></span><br><span class="line"><span class="keyword">var</span> examCarNum = <span class="number">0</span>      <span class="comment">// 驾考车的数量</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 驾考车构造函数 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ExamCar</span>(<span class="params">carType</span>) </span>&#123;</span><br><span class="line">    examCarNum++</span><br><span class="line">    <span class="built_in">this</span>.carId = examCarNum</span><br><span class="line">    <span class="built_in">this</span>.carType = carType ? <span class="string">&#x27;手动档&#x27;</span> : <span class="string">&#x27;自动档&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">ExamCar.prototype.examine = <span class="function"><span class="keyword">function</span>(<span class="params">candidateId</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;考生- &#x27;</span> + candidateId + <span class="string">&#x27; 在&#x27;</span> + <span class="built_in">this</span>.carType + <span class="string">&#x27;驾考车- &#x27;</span> + <span class="built_in">this</span>.carId + <span class="string">&#x27; 上考试&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> candidateId = <span class="number">1</span>; candidateId &lt;= candidateNum; candidateId++) &#123;</span><br><span class="line">    <span class="keyword">var</span> examCar = <span class="keyword">new</span> ExamCar(candidateId % <span class="number">2</span>)</span><br><span class="line">    examCar.examine(candidateId)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;驾考车总数 - &#x27;</span> + examCarNum)</span><br><span class="line"><span class="comment">// 输出: 驾考车总数 - 10</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>如果考生很多，那么系统中就会存在更多个驾考车对象实例，假如驾考车对象比较复杂，那么这些新建的驾考车实例就会占用大量内存。这时我们将同种类型的驾考车实例进行合并，手动档和自动档档驾考车分别引用同一个实例，就可以节约大量内存：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> candidateNum = <span class="number">10</span>   <span class="comment">// 考生数量</span></span><br><span class="line"><span class="keyword">var</span> examCarNum = <span class="number">0</span>      <span class="comment">// 驾考车的数量</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 驾考车构造函数 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ExamCar</span>(<span class="params">carType</span>) </span>&#123;</span><br><span class="line">    examCarNum++</span><br><span class="line">    <span class="built_in">this</span>.carId = examCarNum</span><br><span class="line">    <span class="built_in">this</span>.carType = carType ? <span class="string">&#x27;手动档&#x27;</span> : <span class="string">&#x27;自动档&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">ExamCar.prototype.examine = <span class="function"><span class="keyword">function</span>(<span class="params">candidateId</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;考生- &#x27;</span> + candidateId + <span class="string">&#x27; 在&#x27;</span> + <span class="built_in">this</span>.carType + <span class="string">&#x27;驾考车- &#x27;</span> + <span class="built_in">this</span>.carId + <span class="string">&#x27; 上考试&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> manualExamCar = <span class="keyword">new</span> ExamCar(<span class="literal">true</span>)</span><br><span class="line"><span class="keyword">var</span> autoExamCar = <span class="keyword">new</span> ExamCar(<span class="literal">false</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> candidateId = <span class="number">1</span>; candidateId &lt;= candidateNum; candidateId++) &#123;</span><br><span class="line">    <span class="keyword">var</span> examCar = candidateId % <span class="number">2</span> ? manualExamCar : autoExamCar</span><br><span class="line">    examCar.examine(candidateId)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;驾考车总数 - &#x27;</span> + examCarNum)</span><br><span class="line"><span class="comment">// 输出: 驾考车总数 - 2</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>可以看到我们使用 2 个驾考车实例就实现了刚刚 10 个驾考车实例实现的功能。这是仅有 10 个考生的情况，如果有几百上千考生，这时我们节约的内存就比较可观了，这就是享元模式要达到的目的。</p>
</blockquote>
<p><strong>享元模式的优缺点</strong></p>
<p><strong>享元模式的优点：</strong></p>
<ul>
<li>由于减少了系统中的对象数量，提高了程序运行效率和性能，精简了内存占用，加快运行速度；</li>
<li>外部状态相对独立，不会影响到内部状态，所以享元对象能够在不同的环境被共享；</li>
</ul>
<p><strong>享元模式的缺点：</strong></p>
<ul>
<li>引入了共享对象，使对象结构变得复杂；</li>
<li>共享对象的创建、销毁等需要维护，带来额外的复杂度（如果需要把共享对象维护起来的话）；</li>
</ul>
<p><strong>享元模式的适用场景</strong></p>
<ul>
<li>如果一个程序中大量使用了相同或相似对象，那么可以考虑引入享元模式；</li>
<li>如果使用了大量相同或相似对象，并造成了比较大的内存开销；</li>
<li>对象的大多数状态可以被转变为外部状态；</li>
<li>剥离出对象的外部状态后，可以使用相对较少的共享对象取代大量对象；</li>
<li>在一些程序中，如果引入享元模式对系统的性能和内存的占用影响不大时，比如目标对象不多，或者场景比较简单，则不需要引入，以免适得其反。</li>
</ul>
<p><strong>其他相关模式</strong></p>
<ul>
<li>享元模式和单例模式、工厂模式、组合模式、策略模式、状态模式等等经常会一起使用。</li>
</ul>
<p><strong>享元模式和工厂模式、单例模式</strong></p>
<ul>
<li>在区分出不同种类的外部状态后，创建新对象时需要选择不同种类的共享对象，这时就可以使用工厂模式来提供共享对象，在共享对象的维护上，经常会采用单例模式来提供单实例的共享对象。</li>
</ul>
<p> <strong>享元模式和组合模式</strong></p>
<ul>
<li>在使用工厂模式来提供共享对象时，比如某些时候共享对象中的某些状态就是对象不需要的，可以引入组合模式来提升自定义共享对象的自由度，对共享对象的组成部分进一步归类、分层，来实现更复杂的多层次对象结构，当然系统也会更难维护。</li>
</ul>
<p><strong>享元模式和策略模式</strong></p>
<blockquote>
<p>策略模式中的策略属于一系列功能单一、细粒度的细粒度对象，可以作为目标对象来考虑引入享元模式进行优化，但是前提是这些策略是会被频繁使用的，如果不经常使用，就没有必要了。</p>
</blockquote>
<h2 id="适配器模式"><a href="#适配器模式" class="headerlink" title="适配器模式"></a>适配器模式</h2><ul>
<li>适配器模式（Adapter Pattern）又称包装器模式，将一个类（对象）的接口（方法、属性）转化为用户需要的另一个接口，解决类（对象）之间接口不兼容的问题。</li>
<li>主要功能是进行转换匹配，目的是复用已有的功能，而不是来实现新的接口。也就是说，访问者需要的功能应该是已经实现好了的，不需要适配器模式来实现，适配器模式主要是负责把不兼容的接口转换成访问者期望的格式而已。</li>
</ul>
<p><strong>代码实现</strong></p>
<p>我们可以实现一下电源适配器的例子，一开始我们使用的中国插头标准：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> chinaPlug = &#123;</span><br><span class="line">    type: <span class="string">&#x27;中国插头&#x27;</span>,</span><br><span class="line">    <span class="function"><span class="title">chinaInPlug</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;开始供电&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">chinaPlug.chinaInPlug()</span><br><span class="line"><span class="comment">// 输出：开始供电</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>但是我们出国旅游了，到了日本，需要增加一个日本插头到中国插头的电源适配器，来将我们原来的电源线用起来：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> chinaPlug = &#123;</span><br><span class="line">    type: <span class="string">&#x27;中国插头&#x27;</span>,</span><br><span class="line">    <span class="function"><span class="title">chinaInPlug</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;开始供电&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> japanPlug = &#123;</span><br><span class="line">    type: <span class="string">&#x27;日本插头&#x27;</span>,</span><br><span class="line">    <span class="function"><span class="title">japanInPlug</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;开始供电&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 日本插头电源适配器 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">japanPlugAdapter</span>(<span class="params">plug</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        <span class="function"><span class="title">chinaInPlug</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> plug.japanInPlug()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">japanPlugAdapter(japanPlug).chinaInPlug()</span><br><span class="line"><span class="comment">// 输出：开始供电</span></span><br></pre></td></tr></table></figure>

<p><strong>适配器模式的优缺点</strong></p>
<p><strong>适配器模式的优点：</strong></p>
<ul>
<li>已有的功能如果只是接口不兼容，使用适配器适配已有功能，可以使原有逻辑得到更好的复用，有助于避免大规模改写现有代码；</li>
<li>可扩展性良好，在实现适配器功能的时候，可以调用自己开发的功能，从而方便地扩展系统的功能；</li>
<li>灵活性好，因为适配器并没有对原有对象的功能有所影响，如果不想使用适配器了，那么直接删掉即可，不会对使用原有对象的代码有影响；</li>
<li>适配器模式的缺点：会让系统变得零乱，明明调用 A，却被适配到了 B，如果系统中这样的情况很多，那么对可阅读性不太友好。如果没必要使用适配器模式的话，可以考虑重构，如果使用的话，可以考虑尽量把文档完善。</li>
</ul>
<p><strong>适配器模式的适用场景</strong></p>
<ul>
<li>当你想用已有对象的功能，却想修改它的接口时，一般可以考虑一下是不是可以应用适配器模式。</li>
<li>如果你想要使用一个已经存在的对象，但是它的接口不满足需求，那么可以使用适配器模式，把已有的实现转换成你需要的接口；</li>
<li>如果你想创建一个可以复用的对象，而且确定需要和一些不兼容的对象一起工作，这种情况可以使用适配器模式，然后需要什么就适配什么；</li>
</ul>
<p><strong>其他相关模式</strong></p>
<blockquote>
<p>适配器模式和代理模式、装饰者模式看起来比较类似，都是属于包装模式，也就是用一个对象来包装另一个对象的模式，他们之间的异同在代理模式中已经详细介绍了，这里再简单对比一下。</p>
</blockquote>
<p><strong>适配器模式与代理模式</strong></p>
<ul>
<li>适配器模式： 提供一个不一样的接口，由于原来的接口格式不能用了，提供新的接口以满足新场景下的需求；</li>
<li>代理模式： 提供一模一样的接口，由于不能直接访问目标对象，找个代理来帮忙访问，使用者可以就像访问目标对象一样来访问代理对象；</li>
</ul>
<p><strong>适配器模式、装饰者模式与代理模式</strong></p>
<ul>
<li>适配器模式： 功能不变，只转换了原有接口访问格式；</li>
<li>装饰者模式： 扩展功能，原有功能不变且可直接使用；</li>
<li>代理模式： 原有功能不变，但一般是经过限制访问的；</li>
</ul>
<h2 id="装饰者模式"><a href="#装饰者模式" class="headerlink" title="装饰者模式"></a>装饰者模式</h2><blockquote>
<p>装饰者模式 （Decorator Pattern）又称装饰器模式，在不改变原对象的基础上，通过对其添加属性或方法来进行包装拓展，使得原有对象可以动态具有更多功能。</p>
</blockquote>
<blockquote>
<p>本质是功能动态组合，即动态地给一个对象添加额外的职责，就增加功能角度来看，使用装饰者模式比用继承更为灵活。好处是有效地把对象的核心职责和装饰功能区分开，并且通过动态增删装饰去除目标对象中重复的装饰逻辑。</p>
</blockquote>
<p>我们可以使用 JavaScript 来将装修房子的例子实现一下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 毛坯房 - 目标对象 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">OriginHouse</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">OriginHouse.prototype.getDesc = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;毛坯房&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 搬入家具 - 装饰者 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Furniture</span>(<span class="params">house</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.house = house</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Furniture.prototype.getDesc = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.house.getDesc()</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;搬入家具&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 墙壁刷漆 - 装饰者 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Painting</span>(<span class="params">house</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.house = house</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Painting.prototype.getDesc = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.house.getDesc()</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;墙壁刷漆&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> house = <span class="keyword">new</span> OriginHouse() <span class="comment">// 毛坯房</span></span><br><span class="line">house = <span class="keyword">new</span> Furniture(house) <span class="comment">// 搬入家具</span></span><br><span class="line">house = <span class="keyword">new</span> Painting(house) <span class="comment">// 墙壁刷漆</span></span><br><span class="line"></span><br><span class="line">house.getDesc()</span><br><span class="line"><span class="comment">// 输出： 毛坯房  搬入家具  墙壁刷漆</span></span><br><span class="line">使用 ES6 的 Class 语法：</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 毛坯房 - 目标对象 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">OriginHouse</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">getDesc</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;毛坯房&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 搬入家具 - 装饰者 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Furniture</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">house</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.house = house</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">getDesc</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.house.getDesc()</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;搬入家具&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 墙壁刷漆 - 装饰者 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Painting</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">house</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.house = house</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">getDesc</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.house.getDesc()</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;墙壁刷漆&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> house = <span class="keyword">new</span> OriginHouse()</span><br><span class="line">house = <span class="keyword">new</span> Furniture(house)</span><br><span class="line">house = <span class="keyword">new</span> Painting(house)</span><br><span class="line"></span><br><span class="line">house.getDesc()</span><br><span class="line"><span class="comment">// 输出： 毛坯房  搬入家具  墙壁刷漆</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>是不是感觉很麻烦，装饰个功能这么复杂？我们 JSer 大可不必走这一套面向对象花里胡哨的，毕竟 JavaScript 的优点就是灵活：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 毛坯房 - 目标对象 */</span></span><br><span class="line"><span class="keyword">var</span> originHouse = &#123;</span><br><span class="line">    <span class="function"><span class="title">getDesc</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;毛坯房 &#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 搬入家具 - 装饰者 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">furniture</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;搬入家具 &#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 墙壁刷漆 - 装饰者 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">painting</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;墙壁刷漆 &#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 添加装饰 - 搬入家具 */</span></span><br><span class="line">originHouse.getDesc = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> getDesc = originHouse.getDesc</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        getDesc()</span><br><span class="line">        furniture()</span><br><span class="line">    &#125;</span><br><span class="line">&#125; ()</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 添加装饰 - 墙壁刷漆 */</span></span><br><span class="line">originHouse.getDesc = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> getDesc = originHouse.getDesc</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        getDesc()</span><br><span class="line">        painting()</span><br><span class="line">    &#125;</span><br><span class="line">&#125; ()</span><br><span class="line"></span><br><span class="line">originHouse.getDesc()</span><br><span class="line"><span class="comment">// 输出： 毛坯房  搬入家具  墙壁刷漆</span></span><br></pre></td></tr></table></figure>

<p>简洁明了，且更符合前端日常使用的场景。</p>
<p><strong>装饰者模式的优缺点</strong></p>
<p><strong>装饰者模式的优点：</strong></p>
<ul>
<li>我们经常使用继承的方式来实现功能的扩展，但这样会给系统中带来很多的子类和复杂的继承关系，装饰者模式允许用户在不引起子类数量暴增的前提下动态地修饰对象，添加功能，装饰者和被装饰者之间松耦合，可维护性好；</li>
<li>被装饰者可以使用装饰者动态地增加和撤销功能，可以在运行时选择不同的装饰器，实现不同的功能，灵活性好；</li>
<li>装饰者模式把一系列复杂的功能分散到每个装饰器当中，一般一个装饰器只实现一个功能，可以给一个对象增加多个同样的装饰器，也可以把一个装饰器用来装饰不同的对象，有利于装饰器功能的复用；</li>
<li>可以通过选择不同的装饰者的组合，创造不同行为和功能的结合体，原有对象的代码无须改变，就可以使得原有对象的功能变得更强大和更多样化，符合开闭原则；</li>
</ul>
<p><strong>装饰者模式的缺点：</strong></p>
<ul>
<li>使用装饰者模式时会产生很多细粒度的装饰者对象，这些装饰者对象由于接口和功能的多样化导致系统复杂度增加，功能越复杂，需要的细粒度对象越多；</li>
<li>由于更大的灵活性，也就更容易出错，特别是对于多级装饰的场景，错误定位会更加繁琐；</li>
</ul>
<p><strong>装饰者模式的适用场景</strong></p>
<ul>
<li>如果不希望系统中增加很多子类，那么可以考虑使用装饰者模式；</li>
<li>需要通过对现有的一组基本功能进行排列组合而产生非常多的功能时，采用继承关系很难实现，这时采用装饰者模式可以很好实现；</li>
<li>当对象的功能要求可以动态地添加，也可以动态地撤销，可以考虑使用装饰者模式；</li>
</ul>
<p><strong>其他相关模式</strong> </p>
<p>** 装饰者模式与适配器模式**</p>
<blockquote>
<p>装饰者模式和适配器模式都是属于包装模式，然而他们的意图有些不一样：</p>
</blockquote>
<ul>
<li>装饰者模式： 扩展功能，原有功能还可以直接使用，一般可以给目标对象多次叠加使用多个装饰者；</li>
<li>适配器模式： 功能不变，但是转换了原有接口的访问格式，一般只给目标对象使用一次；</li>
</ul>
<p><strong>装饰者模式与组合模式</strong></p>
<p>这两个模式有相似之处，都涉及到对象的递归调用，从某个角度来说，可以把装饰者模式看做是只有一个组件的组合模式。</p>
<ul>
<li>装饰者模式： 动态地给对象增加功能；</li>
<li>组合模式： 管理组合对象和叶子对象，为它们提供一致的操作接口给客户端，方便客户端的使用；</li>
</ul>
<p><strong>装饰者模式与策略模式</strong></p>
<p>装饰者模式和策略模式都包含有许多细粒度的功能模块，但是他们的使用思路不同：</p>
<ul>
<li>装饰者模式： 可以递归调用，使用多个功能模式，功能之间可以叠加组合使用；</li>
<li>策略模式： 只有一层选择，选择某一个功能；</li>
</ul>
<h2 id="外观模式"><a href="#外观模式" class="headerlink" title="外观模式"></a>外观模式</h2><blockquote>
<p>外观模式 （Facade Pattern）又叫门面模式，定义一个将子系统的一组接口集成在一起的高层接口，以提供一个一致的外观。外观模式让外界减少与子系统内多个模块的直接交互，从而减少耦合，让外界可以更轻松地使用子系统。本质是封装交互，简化调用。</p>
</blockquote>
<p>外观模式在源码中使用很多，具体可以参考后文中源码阅读部分。</p>
<p><strong>简化版本的代码： 无人机</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> uav = &#123;</span><br><span class="line">    <span class="comment">/* 电子调速器 */</span></span><br><span class="line">    diantiao1: &#123;</span><br><span class="line">        <span class="function"><span class="title">up</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;电调1发送指令：电机1增大转速&#x27;</span>)</span><br><span class="line">            uav.dianji1.up()</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="function"><span class="title">down</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;电调1发送指令：电机1减小转速&#x27;</span>)</span><br><span class="line">            uav.dianji1.up()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    diantiao2: &#123;</span><br><span class="line">        <span class="function"><span class="title">up</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;电调2发送指令：电机2增大转速&#x27;</span>)</span><br><span class="line">            uav.dianji2.up()</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="function"><span class="title">down</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;电调2发送指令：电机2减小转速&#x27;</span>)</span><br><span class="line">            uav.dianji2.down()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    diantiao3: &#123;</span><br><span class="line">        <span class="function"><span class="title">up</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;电调3发送指令：电机3增大转速&#x27;</span>)</span><br><span class="line">            uav.dianji3.up()</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="function"><span class="title">down</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;电调3发送指令：电机3减小转速&#x27;</span>)</span><br><span class="line">            uav.dianji3.down()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    diantiao4: &#123;</span><br><span class="line">        <span class="function"><span class="title">up</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;电调4发送指令：电机4增大转速&#x27;</span>)</span><br><span class="line">            uav.dianji4.up()</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="function"><span class="title">down</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;电调4发送指令：电机4减小转速&#x27;</span>)</span><br><span class="line">            uav.dianji4.down()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/* 电机 */</span></span><br><span class="line">    dianji1: &#123;</span><br><span class="line">        <span class="function"><span class="title">up</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;电机1增大转速&#x27;</span>) &#125;,</span><br><span class="line">        <span class="function"><span class="title">down</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;电机1减小转速&#x27;</span>) &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    dianji2: &#123;</span><br><span class="line">        <span class="function"><span class="title">up</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;电机2增大转速&#x27;</span>) &#125;,</span><br><span class="line">        <span class="function"><span class="title">down</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;电机2减小转速&#x27;</span>) &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    dianji3: &#123;</span><br><span class="line">        <span class="function"><span class="title">up</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;电机3增大转速&#x27;</span>) &#125;,</span><br><span class="line">        <span class="function"><span class="title">down</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;电机3减小转速&#x27;</span>) &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    dianji4: &#123;</span><br><span class="line">        <span class="function"><span class="title">up</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;电机4增大转速&#x27;</span>) &#125;,</span><br><span class="line">        <span class="function"><span class="title">down</span>(<span class="params"></span>)</span> &#123; <span class="built_in">console</span>.log(<span class="string">&#x27;电机4减小转速&#x27;</span>) &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/* 遥控器 */</span></span><br><span class="line">    controller: &#123;</span><br><span class="line">        <span class="comment">/* 上升 */</span></span><br><span class="line">        <span class="function"><span class="title">up</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            uav.diantiao1.up()</span><br><span class="line">            uav.diantiao2.up()</span><br><span class="line">            uav.diantiao3.up()</span><br><span class="line">            uav.diantiao4.up()</span><br><span class="line">        &#125;,</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* 前进 */</span></span><br><span class="line">        <span class="function"><span class="title">forward</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            uav.diantiao1.down()</span><br><span class="line">            uav.diantiao2.down()</span><br><span class="line">            uav.diantiao3.up()</span><br><span class="line">            uav.diantiao4.up()</span><br><span class="line">        &#125;,</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* 下降 */</span></span><br><span class="line">        <span class="function"><span class="title">down</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            uav.diantiao1.down()</span><br><span class="line">            uav.diantiao2.down()</span><br><span class="line">            uav.diantiao3.down()</span><br><span class="line">            uav.diantiao4.down()</span><br><span class="line">        &#125;,</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* 左转 */</span></span><br><span class="line">        <span class="function"><span class="title">left</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            uav.diantiao1.up()</span><br><span class="line">            uav.diantiao2.down()</span><br><span class="line">            uav.diantiao3.up()</span><br><span class="line">            uav.diantiao4.down()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 操纵无人机 */</span></span><br><span class="line">uav.controller.down()    <span class="comment">// 发送下降指令</span></span><br><span class="line">uav.controller.left()    <span class="comment">// 发送左转指令</span></span><br></pre></td></tr></table></figure>

<p>无人机系统是比较复杂，但是可以看到无人机的操纵却比较简单，正是因为有遥控器这个外观的存在。</p>
<p><strong>外观模式的优点：</strong></p>
<ul>
<li>访问者不需要再了解子系统内部模块的功能，而只需和外观交互即可，使得访问者对子系统的使用变得简单，符合最少知识原则，增强了可移植性和可读性；</li>
<li>减少了与子系统模块的直接引用，实现了访问者与子系统中模块之间的松耦合，增加了可维护性和可扩展性；</li>
<li>通过合理使用外观模式，可以帮助我们更好地划分系统访问层次，比如把需要暴露给外部的功能集中到外观中，这样既方便访问者使用，也很好地隐藏了内部的细节，提升了安全性；</li>
</ul>
<p><strong>外观模式的缺点：</strong></p>
<ul>
<li>不符合开闭原则，对修改关闭，对扩展开放，如果外观模块出错，那么只能通过修改的方式来解决问题，因为外观模块是子系统的唯一出口；</li>
<li>不需要或不合理的使用外观会让人迷惑，过犹不及；</li>
</ul>
<p><strong>外观模式的适用场景</strong></p>
<ul>
<li>维护设计粗糙和难以理解的遗留系统，或者系统非常复杂的时候，可以为这些系统设置外观模块，给外界提供清晰的接口，以后新系统只需与外观交互即可；</li>
<li>你写了若干小模块，可以完成某个大功能，但日后常用的是大功能，可以使用外观来提供大功能，因为外界也不需要了解小模块的功能；</li>
<li>团队协作时，可以给各自负责的模块建立合适的外观，以简化使用，节约沟通时间；</li>
<li>如果构建多层系统，可以使用外观模式来将系统分层，让外观模块成为每层的入口，简化层间调用，松散层间耦合；</li>
</ul>
<p><strong>其他相关模式</strong> </p>
<p><strong>外观模式与中介者模式</strong></p>
<ul>
<li>外观模式： 封装子使用者对子系统内模块的直接交互，方便使用者对子系统的调用；</li>
<li>中介者模式： 封装子系统间各模块之间的直接交互，松散模块间的耦合；</li>
</ul>
<p><strong>外观模式与单例模式</strong></p>
<blockquote>
<p>有时候一个系统只需要一个外观，比如之前举的 <code>Axios</code> 的 <code>HTTP</code> 模块例子。这时我们可以将外观模式和单例模式可以一起使用，把外观实现为单例。</p>
</blockquote>
<h2 id="组合模式"><a href="#组合模式" class="headerlink" title="组合模式"></a>组合模式</h2><blockquote>
<p>组合模式 （Composite Pattern）又叫整体-部分模式，它允许你将对象组合成树形结构来表现整体-部分层次结构，让使用者可以以一致的方式处理组合对象以及部分对象</p>
</blockquote>
<p><strong>你曾见过的组合模式</strong></p>
<p>大家电脑里的文件夹结构相比很熟悉了，文件夹下面可以有子文件夹，也可以有文件，子文件夹下面还可以有文件夹和文件，以此类推，共同组成了一个文件树，结构如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">Folder <span class="number">1</span></span><br><span class="line">├── Folder <span class="number">2</span></span><br><span class="line">│   ├── File <span class="number">1.</span>txt</span><br><span class="line">│   ├── File <span class="number">2.</span>txt</span><br><span class="line">│   └── File <span class="number">3.</span>txt</span><br><span class="line">└── Folder <span class="number">3</span></span><br><span class="line">    ├── File <span class="number">4.</span>txt</span><br><span class="line">    ├── File <span class="number">5.</span>txt</span><br><span class="line">    └── File <span class="number">6.</span>txt</span><br></pre></td></tr></table></figure>

<blockquote>
<p>文件夹是树形结构的容器节点，容器节点可以继续包含其他容器节点，像树枝上还可以有其他树枝一样；也可以包含文件，不再增加新的层级，就像树的叶子一样处于末端，因此被称为叶节点。本文中，叶节点又称为叶对象，容器节点因为可以包含容器节点和非容器节点，又称为组合对象。</p>
</blockquote>
<p><strong>代码实现</strong></p>
<p>我们可以使用 JavaScript 来将之前的文件夹例子实现一下。</p>
<p>在本地一个「电影」文件夹下有两个子文件夹「漫威英雄电影」和「DC英雄电影」，分别各自有一些电影文件，我们要做的就是在这个电影文件夹里找大于 2G 的电影文件，无论是在这个文件夹下还是在子文件夹下，并输出它的文件名和文件大小。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 创建文件夹 */</span></span><br><span class="line"><span class="keyword">var</span> createFolder = <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        name: name,</span><br><span class="line">        _children: [],</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* 在文件夹下增加文件或文件夹 */</span></span><br><span class="line">        <span class="function"><span class="title">add</span>(<span class="params">fileOrFolder</span>)</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>._children.push(fileOrFolder)</span><br><span class="line">        &#125;,</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* 扫描方法 */</span></span><br><span class="line">        <span class="function"><span class="title">scan</span>(<span class="params">cb</span>)</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>._children.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">child</span>) </span>&#123;</span><br><span class="line">                child.scan(cb)</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 创建文件 */</span></span><br><span class="line"><span class="keyword">var</span> createFile = <span class="function"><span class="keyword">function</span>(<span class="params">name, size</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        name: name,</span><br><span class="line">        size: size,</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* 在文件下增加文件，应报错 */</span></span><br><span class="line">        <span class="function"><span class="title">add</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;文件下面不能再添加文件&#x27;</span>)</span><br><span class="line">        &#125;,</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* 执行扫描方法 */</span></span><br><span class="line">        <span class="function"><span class="title">scan</span>(<span class="params">cb</span>)</span> &#123;</span><br><span class="line">            cb(<span class="built_in">this</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> foldMovies = createFolder(<span class="string">&#x27;电影&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建子文件夹，并放入根文件夹</span></span><br><span class="line"><span class="keyword">var</span> foldMarvelMovies = createFolder(<span class="string">&#x27;漫威英雄电影&#x27;</span>)</span><br><span class="line">foldMovies.add(foldMarvelMovies)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> foldDCMovies = createFolder(<span class="string">&#x27;DC英雄电影&#x27;</span>)</span><br><span class="line">foldMovies.add(foldDCMovies)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 为两个子文件夹分别添加电影</span></span><br><span class="line">foldMarvelMovies.add(createFile(<span class="string">&#x27;钢铁侠.mp4&#x27;</span>, <span class="number">1.9</span>))</span><br><span class="line">foldMarvelMovies.add(createFile(<span class="string">&#x27;蜘蛛侠.mp4&#x27;</span>, <span class="number">2.1</span>))</span><br><span class="line">foldMarvelMovies.add(createFile(<span class="string">&#x27;金刚狼.mp4&#x27;</span>, <span class="number">2.3</span>))</span><br><span class="line">foldMarvelMovies.add(createFile(<span class="string">&#x27;黑寡妇.mp4&#x27;</span>, <span class="number">1.9</span>))</span><br><span class="line">foldMarvelMovies.add(createFile(<span class="string">&#x27;美国队长.mp4&#x27;</span>, <span class="number">1.4</span>))</span><br><span class="line"></span><br><span class="line">foldDCMovies.add(createFile(<span class="string">&#x27;蝙蝠侠.mp4&#x27;</span>, <span class="number">2.4</span>))</span><br><span class="line">foldDCMovies.add(createFile(<span class="string">&#x27;超人.mp4&#x27;</span>, <span class="number">1.6</span>))</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;size 大于2G的文件有：&#x27;</span>)</span><br><span class="line">foldMovies.scan(<span class="function"><span class="keyword">function</span>(<span class="params">item</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (item.size &gt; <span class="number">2</span>) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;name:&#x27;</span> + item.name + <span class="string">&#x27; size:&#x27;</span> + item.size + <span class="string">&#x27;GB&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// size 大于2G的文件有：</span></span><br><span class="line"><span class="comment">// name:蜘蛛侠.mp4 size:2.1GB</span></span><br><span class="line"><span class="comment">// name:金刚狼.mp4 size:2.3GB</span></span><br><span class="line"><span class="comment">// name:蝙蝠侠.mp4 size:2.4GB</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>作为灵活的 JavaScript，我们还可以使用链模式来进行改造一下，让我们添加子文件更加直观和方便。对链模式还不熟悉的同学可以看一下后面有一篇单独介绍链模式的文章～</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 创建文件夹 */</span></span><br><span class="line"><span class="keyword">const</span> createFolder = <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        name: name,</span><br><span class="line">        _children: [],</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* 在文件夹下增加文件或文件夹  */</span></span><br><span class="line">        <span class="function"><span class="title">add</span>(<span class="params">...fileOrFolder</span>)</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>._children.push(...fileOrFolder)</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">this</span></span><br><span class="line">        &#125;,</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* 扫描方法 */</span></span><br><span class="line">        <span class="function"><span class="title">scan</span>(<span class="params">cb</span>)</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>._children.forEach(<span class="function"><span class="params">child</span> =&gt;</span> child.scan(cb))</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 创建文件 */</span></span><br><span class="line"><span class="keyword">const</span> createFile = <span class="function"><span class="keyword">function</span>(<span class="params">name, size</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        name: name,</span><br><span class="line">        size: size,</span><br><span class="line">      </span><br><span class="line">        <span class="comment">/* 在文件下增加文件，应报错 */</span></span><br><span class="line">        <span class="function"><span class="title">add</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;文件下面不能再添加文件&#x27;</span>)</span><br><span class="line">        &#125;,</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* 执行扫描方法 */</span></span><br><span class="line">        <span class="function"><span class="title">scan</span>(<span class="params">cb</span>)</span> &#123;</span><br><span class="line">            cb(<span class="built_in">this</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> foldMovies = createFolder(<span class="string">&#x27;电影&#x27;</span>)</span><br><span class="line">  .add(</span><br><span class="line">    createFolder(<span class="string">&#x27;漫威英雄电影&#x27;</span>)</span><br><span class="line">      .add(createFile(<span class="string">&#x27;钢铁侠.mp4&#x27;</span>, <span class="number">1.9</span>))</span><br><span class="line">      .add(createFile(<span class="string">&#x27;蜘蛛侠.mp4&#x27;</span>, <span class="number">2.1</span>))</span><br><span class="line">      .add(createFile(<span class="string">&#x27;金刚狼.mp4&#x27;</span>, <span class="number">2.3</span>))</span><br><span class="line">      .add(createFile(<span class="string">&#x27;黑寡妇.mp4&#x27;</span>, <span class="number">1.9</span>))</span><br><span class="line">      .add(createFile(<span class="string">&#x27;美国队长.mp4&#x27;</span>, <span class="number">1.4</span>)),</span><br><span class="line">    createFolder(<span class="string">&#x27;DC英雄电影&#x27;</span>)</span><br><span class="line">      .add(createFile(<span class="string">&#x27;蝙蝠侠.mp4&#x27;</span>, <span class="number">2.4</span>))</span><br><span class="line">      .add(createFile(<span class="string">&#x27;超人.mp4&#x27;</span>, <span class="number">1.6</span>))</span><br><span class="line">  )</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;size 大于2G的文件有：&#x27;</span>)</span><br><span class="line"></span><br><span class="line">foldMovies.scan(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (item.size &gt; <span class="number">2</span>) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`name:<span class="subst">$&#123; item.name &#125;</span> size:<span class="subst">$&#123; item.size &#125;</span>GB`</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// size 大于2G的文件有：</span></span><br><span class="line"><span class="comment">// name:蜘蛛侠.mp4 size:2.1GB</span></span><br><span class="line"><span class="comment">// name:金刚狼.mp4 size:2.3GB</span></span><br><span class="line"><span class="comment">// name:蝙蝠侠.mp4 size:2.4GB</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>上面的代码比较 JavaScript 特色，如果我们使用传统的类呢，也是可以实现的，下面使用 ES6 的 class 语法来改写一下：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 文件夹类 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Folder</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name, children</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name</span><br><span class="line">        <span class="built_in">this</span>.children = children</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 在文件夹下增加文件或文件夹 */</span></span><br><span class="line">    <span class="function"><span class="title">add</span>(<span class="params">...fileOrFolder</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.children.push(...fileOrFolder)</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 扫描方法 */</span></span><br><span class="line">    <span class="function"><span class="title">scan</span>(<span class="params">cb</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.children.forEach(<span class="function"><span class="params">child</span> =&gt;</span> child.scan(cb))</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 文件类 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">File</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name, size</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name</span><br><span class="line">        <span class="built_in">this</span>.size = size</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 在文件下增加文件，应报错 */</span></span><br><span class="line">    <span class="function"><span class="title">add</span>(<span class="params">...fileOrFolder</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;文件下面不能再添加文件&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 执行扫描方法 */</span></span><br><span class="line">    <span class="function"><span class="title">scan</span>(<span class="params">cb</span>)</span> &#123;</span><br><span class="line">        cb(<span class="built_in">this</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> foldMovies = <span class="keyword">new</span> Folder(<span class="string">&#x27;电影&#x27;</span>, [</span><br><span class="line">    <span class="keyword">new</span> Folder(<span class="string">&#x27;漫威英雄电影&#x27;</span>, [</span><br><span class="line">        <span class="keyword">new</span> File(<span class="string">&#x27;钢铁侠.mp4&#x27;</span>, <span class="number">1.9</span>),</span><br><span class="line">        <span class="keyword">new</span> File(<span class="string">&#x27;蜘蛛侠.mp4&#x27;</span>, <span class="number">2.1</span>),</span><br><span class="line">        <span class="keyword">new</span> File(<span class="string">&#x27;金刚狼.mp4&#x27;</span>, <span class="number">2.3</span>),</span><br><span class="line">        <span class="keyword">new</span> File(<span class="string">&#x27;黑寡妇.mp4&#x27;</span>, <span class="number">1.9</span>),</span><br><span class="line">        <span class="keyword">new</span> File(<span class="string">&#x27;美国队长.mp4&#x27;</span>, <span class="number">1.4</span>)]),</span><br><span class="line">    <span class="keyword">new</span> Folder(<span class="string">&#x27;DC英雄电影&#x27;</span>, [</span><br><span class="line">        <span class="keyword">new</span> File(<span class="string">&#x27;蝙蝠侠.mp4&#x27;</span>, <span class="number">2.4</span>),</span><br><span class="line">        <span class="keyword">new</span> File(<span class="string">&#x27;超人.mp4&#x27;</span>, <span class="number">1.6</span>)])</span><br><span class="line">])</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;size 大于2G的文件有：&#x27;</span>)</span><br><span class="line"></span><br><span class="line">foldMovies.scan(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (item.size &gt; <span class="number">2</span>) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`name:<span class="subst">$&#123; item.name &#125;</span> size:<span class="subst">$&#123; item.size &#125;</span>GB`</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// size 大于2G的文件有：</span></span><br><span class="line"><span class="comment">// name:蜘蛛侠.mp4 size:2.1GB</span></span><br><span class="line"><span class="comment">// name:金刚狼.mp4 size:2.3GB</span></span><br><span class="line"><span class="comment">// name:蝙蝠侠.mp4 size:2.4GB</span></span><br></pre></td></tr></table></figure>

<p>在传统的语言中，为了保证叶对象和组合对象的外观一致，还会让他们实现同一个抽象类或接口。</p>
<p><strong>组合模式的优缺点</strong> <strong>组合模式的优点：</strong></p>
<ul>
<li>由于组合对象和叶对象具有同样的接口，因此调用的是组合对象还是叶对象对使用者来说没有区别，使得使用者面向接口编程；</li>
<li>如果想在组合模式的树中增加一个节点比较容易，在目标组合对象中添加即可，不会影响到其他对象，对扩展友好，符合开闭原则，利于维护；</li>
</ul>
<p><strong>组合模式的缺点：</strong></p>
<ul>
<li>增加了系统复杂度，如果树中对象不多，则不一定需要使用；</li>
<li>如果通过组合模式创建了太多的对象，那么这些对象可能会让系统负担不起；</li>
</ul>
<p><strong>组合模式的适用场景</strong></p>
<ul>
<li>如果对象组织呈树形结构就可以考虑使用组合模式，特别是如果操作树中对象的方法比较类似时；</li>
<li>使用者希望统一对待树形结构中的对象，比如用户不想写一堆 if-else 来处理树中的节点时，可以使用组合模式；</li>
</ul>
<p><strong>其他相关模式</strong> </p>
<p><strong>组合模式和职责链模式</strong></p>
<p>正如前文所说，组合模式是天生实现了职责链模式的。</p>
<ul>
<li>组合模式： 请求在组合对象上传递，被深度遍历到组合对象的所有子孙叶节点具体执行；</li>
<li>职责链模式： 实现请求的发送者和接受者之间的解耦，把多个接受者组合起来形成职责链，请求在链上传递，直到有接受者处理请求为止；</li>
</ul>
<p><strong>组合模式和迭代器模式</strong></p>
<p>组合模式可以结合迭代器模式一起使用，在遍历组合对象的叶节点的时候，可以使用迭代器模式来遍历。</p>
<p><strong>组合模式和命令模式</strong></p>
<blockquote>
<p>命令模式里有一个用法「宏命令」，宏命令就是组合模式和命令模式一起使用的结果，是组合模式组装而成</p>
</blockquote>
<h2 id="桥接模式"><a href="#桥接模式" class="headerlink" title="桥接模式"></a>桥接模式</h2><ul>
<li>桥接模式（Bridge Pattern）又称桥梁模式，将抽象部分与它的实现部分分离，使它们都可以独立地变化。使用组合关系代替继承关系，降低抽象和实现两个可变维度的耦合度。</li>
<li>抽象部分和实现部分可能不太好理解，举个例子，香蕉、苹果、西瓜，它们共同的抽象部分就是水果，可以吃，实现部分就是不同的水果实体。再比如黑色手提包、红色钱包、蓝色公文包，它们共同的抽象部分是包和颜色，这部分的共性就可以被作为抽象提取出来。</li>
</ul>
<p><strong>实例的代码实现</strong></p>
<p>我们可以使用 JavaScript 来将之前的变频洗衣机例子实现一下。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 组装洗衣机 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Washer</span>(<span class="params">motorType, rollerType, transducerType</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.motor = <span class="keyword">new</span> Motor(motorType)</span><br><span class="line">    <span class="built_in">this</span>.roller = <span class="keyword">new</span> Roller(rollerType)</span><br><span class="line">    <span class="built_in">this</span>.transducer = <span class="keyword">new</span> Transducer(transducerType)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Washer.prototype.work = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.motor.run()</span><br><span class="line">    <span class="built_in">this</span>.roller.run()</span><br><span class="line">    <span class="built_in">this</span>.transducer.run()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 电机 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Motor</span>(<span class="params">type</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.motorType = type + <span class="string">&#x27;电机&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Motor.prototype.run = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.motorType + <span class="string">&#x27;开始工作&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 滚筒 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Roller</span>(<span class="params">type</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.rollerType = type + <span class="string">&#x27;滚筒&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Roller.prototype.run = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.rollerType + <span class="string">&#x27;开始工作&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 变频器 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Transducer</span>(<span class="params">type</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.transducerType = type + <span class="string">&#x27;变频器&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Transducer.prototype.run = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.transducerType + <span class="string">&#x27;开始工作&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 新建洗衣机</span></span><br><span class="line"><span class="keyword">var</span> washerA = <span class="keyword">new</span> Washer(<span class="string">&#x27;小功率&#x27;</span>, <span class="string">&#x27;直立&#x27;</span>, <span class="string">&#x27;小功率&#x27;</span>)</span><br><span class="line">washerA.work()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出：小功率电机开始工作</span></span><br><span class="line"><span class="comment">//      直立滚筒开始工作</span></span><br><span class="line"><span class="comment">//      小功率变频器开始工作</span></span><br><span class="line">由于产品部件可以独立变化，所以创建新的洗衣机产品就非常容易：</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> washerD = <span class="keyword">new</span> Washer(<span class="string">&#x27;小功率&#x27;</span>, <span class="string">&#x27;直立&#x27;</span>, <span class="string">&#x27;中功率&#x27;</span>)</span><br><span class="line">washerD.work()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出：小功率电机开始工作</span></span><br><span class="line"><span class="comment">//      直立滚筒开始工作</span></span><br><span class="line"><span class="comment">//      中功率变频器开始工作</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>可以看到由于洗衣机的结构被分别抽象为几个部件的组合，部件的实例化是在部件类各自的构造函数中完成，因此部件之间的实例化不会相互影响，新产品的创建也变得容易，这就是桥接模式的好处。</p>
</blockquote>
<p>下面我们用 ES6 的 Class 语法实现一下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 组装洗衣机 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Washer</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">motorType, rollerType, transducerType</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.motor = <span class="keyword">new</span> Motor(motorType)</span><br><span class="line">        <span class="built_in">this</span>.roller = <span class="keyword">new</span> Roller(rollerType)</span><br><span class="line">        <span class="built_in">this</span>.transducer = <span class="keyword">new</span> Transducer(transducerType)</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/* 开始使用 */</span></span><br><span class="line">    <span class="function"><span class="title">work</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.motor.run()</span><br><span class="line">        <span class="built_in">this</span>.roller.run()</span><br><span class="line">        <span class="built_in">this</span>.transducer.run()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 电机 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Motor</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">type</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.motorType = type + <span class="string">&#x27;电机&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">run</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.motorType + <span class="string">&#x27;开始工作&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 滚筒 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Roller</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">type</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.rollerType = type + <span class="string">&#x27;滚筒&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">run</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.rollerType + <span class="string">&#x27;开始工作&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 变频器 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Transducer</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">type</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.transducerType = type + <span class="string">&#x27;变频器&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">run</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.transducerType + <span class="string">&#x27;开始工作&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> washerA = <span class="keyword">new</span> Washer(<span class="string">&#x27;小功率&#x27;</span>, <span class="string">&#x27;直立&#x27;</span>, <span class="string">&#x27;小功率&#x27;</span>)</span><br><span class="line">washerA.work()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出：小功率电机开始工作</span></span><br><span class="line"><span class="comment">//      直立滚筒开始工作</span></span><br><span class="line"><span class="comment">//      小功率变频器开始工作</span></span><br></pre></td></tr></table></figure>

<ul>
<li>如果再精致一点，可以让电机、滚筒、变频器等部件实例继承自各自的抽象类，将面向抽象进行到底，但是桥接模式在 JavaScript 中应用不多，适当了解即可，不用太死扣。</li>
<li>有时候为了更复用部件，可以将部件的实例化拿出来，对于洗衣机来说一个实体部件当然不能用两次，这里使用皮包的例子：</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 皮包 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Bag</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">type, color</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.type = type</span><br><span class="line">        <span class="built_in">this</span>.color = color</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/* 展示 */</span></span><br><span class="line">    <span class="function"><span class="title">show</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(</span><br><span class="line">          <span class="built_in">this</span>.color.show() + <span class="built_in">this</span>.type.show()</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 皮包类型 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Type</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">type</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.typeType = type</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">show</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.typeType</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 皮包颜色 */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Color</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">type</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.colorType = type</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="title">show</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.colorType</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 抽象实例化 */</span></span><br><span class="line"><span class="keyword">const</span> redColor = <span class="keyword">new</span> Color(<span class="string">&#x27;红色&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> walletType = <span class="keyword">new</span> Type(<span class="string">&#x27;钱包&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> briefcaseType = <span class="keyword">new</span> Type(<span class="string">&#x27;公文包&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> bagA = <span class="keyword">new</span> Bag(walletType, redColor)</span><br><span class="line">bagA.show()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出：红色钱包</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> bagB = <span class="keyword">new</span> Bag(briefcaseType, redColor)</span><br><span class="line">bagB.show()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出：红色公文包</span></span><br></pre></td></tr></table></figure>

<h1 id="四、行为型模式"><a href="#四、行为型模式" class="headerlink" title="四、行为型模式"></a><strong>四、行为型模式</strong></h1><p>暂时搞不懂，后续理解</p>
<h1 id="五、其他模式"><a href="#五、其他模式" class="headerlink" title="五、其他模式"></a><strong>五、其他模式</strong></h1><h2 id="MVC、MVP、MVVM"><a href="#MVC、MVP、MVVM" class="headerlink" title="MVC、MVP、MVVM"></a>MVC、MVP、MVVM</h2><blockquote>
<p>在下文中，如果某些内容和你看的某本书或者某个帖子上的不一样，不要惊慌，多看几本书，多打开几个帖子，你会发现每个都不一样，所以模式具体是如何表现并不重要，重要的是，了解这三个模式主要的目的和思想是什么：</p>
</blockquote>
<ul>
<li><code>MVC</code> 模式： 从大锅烩时代进化，引入了分层的概念，但是层与层之间耦合明显，维护起来不容易；</li>
<li><code>MVP</code> 模式： 在 MVC 基础上进一步解耦，视图层和模型层完全隔离，交互只能通过管理层来进行，问题是更新视图需要管理层手动来进行；</li>
<li><code>MVVM</code> 模式： 引入双向绑定机制，帮助实现一些更新视图层和模型层的工作，让开发者可以更专注于业务逻辑，相比于之前的模式，可以使用更少的代码量完成更复杂的交互； MVC、MVP、MVVM 模式是我们经常遇到的概念，其中 MVVM 是最常用到的，在实际项目中往往没有严格按照模式的定义来设计的系统，开发中也不一定要纠结自己用的到底是哪个模式，合适的才是最好的。</li>
</ul>
<h3 id="1-MVC-（Model-View-Controller）"><a href="#1-MVC-（Model-View-Controller）" class="headerlink" title="1. MVC （Model View Controller）"></a><strong>1. MVC （Model View Controller）</strong></h3><blockquote>
<p><code>MVC</code> 模式将程序分为三个部分：模型（<code>Model</code>）、视图（<code>View</code>）、控制器（<code>Controller</code>）。</p>
</blockquote>
<ul>
<li><code>Model</code> 模型层： 业务数据的处理和存储，数据更新后更新；</li>
<li><code>View</code> 视图层： 人机交互接口，一般为展示给用户的界面；</li>
<li><code>Controller</code> 控制器层 ： 负责连接 <code>Model</code> 层和 <code>View</code> 层，接受并处理 <code>View</code> 层触发的事件，并在 <code>Model</code> 层的数据状态变动时更新 <code>View</code> 层；</li>
<li><code>MVC</code> 模式的目的是通过引入 <code>Controller</code> 层来将 <code>Model</code> 层和 <code>View</code> 层分离，分层的引入是原来大锅烩方式的改进，使得系统在可维护性和可读性上有了进步。</li>
<li><code>MVC</code> 模式提出已经有四十余年，<code>MVC</code> 模式在各个书、各个教程、<code>WIKI</code> 的解释有各种版本，甚至 <code>MVC</code> 模式在不同系统中的具体表现也不同，这里只介绍典型 <code>MVC</code> 模式的思路。</li>
</ul>
<blockquote>
<p>典型思路是 <code>View</code> 层通过事件通知到 <code>Controller</code> 层，<code>Controller</code> 层经过对事件的处理完成相关业务逻辑，要求 <code>Model</code> 层改变数据状态，<code>Model</code> 层再将新数据更新到 <code>View</code>层。</p>
</blockquote>
<p>在实际操作时，用户可以直接对 <code>View</code> 层的 <code>UI</code> 进行操作，以通过事件通知 <code>Controller</code> 层，经过处理后修改 <code>Model</code> 层的数据，<code>Model</code> 层使用最新数据更新 <code>View</code>。</p>
<p>用户也可以直接触发 <code>Controller</code> 去更新 <code>Model</code> 层状态，再更新 View 层</p>
<p>某些场景下，<code>View</code> 层直接采用观察者/发布订阅模式监听 <code>Model</code> 层的变化，这样 <code>View</code>层和 <code>Model</code> 层相互持有、相互操作，导致紧密耦合，在可维护性上有待提升。由此，<code>MVP</code> 模式应运而生 。</p>
<h3 id="2-MVP-（Model-View-Presenter）"><a href="#2-MVP-（Model-View-Presenter）" class="headerlink" title="2. MVP （Model View Presenter）"></a><strong>2. MVP （Model View Presenter）</strong></h3><blockquote>
<p><code>MVP</code> 模式将程序分为三个部分：模型（<code>Model</code>）、视图（<code>View</code>）、管理层（<code>Presenter</code>）。</p>
</blockquote>
<ul>
<li><code>Model</code> 模型层： 只负责存储数据，与 <code>View</code> 呈现无关，也与 <code>UI</code> 处理逻辑无关，发生更新也不用主动通知 <code>View</code>；</li>
<li><code>View</code> 视图层： 人机交互接口，一般为展示给用户的界面；</li>
<li><code>Presenter</code> 管理层 ： 负责连接 <code>Model</code> 层和 <code>View</code> 层，处理 <code>View</code> 层的事件，负责获取数据并将获取的数据经过处理后更新 <code>View</code>；</li>
<li><code>MVC</code> 模式的 <code>View</code> 层和 <code>Model</code> 层存在耦合，为了解决这个问题，<code>MVP</code> 模式将 <code>View</code> 层和 <code>Model</code> 层解耦，之间的交互只能通过 <code>Presenter</code> 层，实际上，<code>MVP</code> 模式的目的就是将 <code>View</code> 层和 Model 层完全解耦，使得对 <code>View</code> 层的修改不会影响到 <code>Model</code> 层，而对 <code>Model</code> 层的数据改动也不会影响到<code>View</code> 层。</li>
</ul>
<blockquote>
<p>典型流程是 <code>View</code> 层触发的事件传递到 <code>Presenter</code> 层中处理，<code>Presenter</code> 层去操作 <code>Model</code> 层，并且将数据返回给 <code>View</code>层，这个过程中，<code>View</code> 层和 <code>Model</code> 层没有直接联系。而 <code>View</code> 层不部署业务逻辑，除了展示数据和触发事件之外，其它时间都在等着 <code>Presenter</code> 层来更新自己，被称为「被动视图」。</p>
</blockquote>
<p>在实际操作时，用户可以直接对 <code>View</code> 层的 <code>UI</code> 进行操作，<code>View</code> 层通知 <code>Presenter</code> 层，<code>Presenter</code> 层操作 <code>Model</code> 层的数据，<code>Presenter</code> 层获取到数据之后更新 <code>View</code>。</p>
<ul>
<li>由于 <code>Presenter</code> 层负责了数据获取、数据处理、交互逻辑、<code>UI</code> 效果等等功能，所以 <code>Presenter</code> 层就变得强大起来，相应的，<code>Model</code> 层只负责数据存储，而 <code>View</code> 层只负责视图，<code>Model</code> 和 <code>View</code> 层的责任纯粹而单一，如果我们需要添加或修改功能模块，只需要修改 <code>Presenter</code> 层就够了。由于 <code>Presenter</code> 层需要调用 <code>View</code> 层的方法更新视图，<code>Presenter</code> 层直接持有 <code>View</code> 层导致了 <code>Presenter</code> 对 <code>View</code> 的依赖。</li>
</ul>
<blockquote>
<p>正如上所说，更新视图需要 <code>Presenter</code> 层直接持有 <code>View</code> 层，并通过调用 <code>View</code> 层中的方法来实现，还是需要一系列复杂操作，有没有什么机制自动去更新视图而不用我们手动去更新呢，所以，<code>MVVM</code> 模式应运而生。</p>
</blockquote>
<h3 id="3-MVVM-（Model-View-ViewModel）"><a href="#3-MVVM-（Model-View-ViewModel）" class="headerlink" title="3. MVVM （Model View ViewModel）"></a><strong>3. MVVM （Model View ViewModel）</strong></h3><blockquote>
<p><code>MVVM</code> 模式将程序分为三个部分：模型（<code>Model</code>）、视图（<code>View</code>）、视图模型（<code>View-Model</code>）。</p>
</blockquote>
<p>和 <code>MVP</code> 模式类似，<code>Model</code> 层和 <code>View</code> 层也被隔离开，彻底解耦，<code>ViewModel</code> 层相当于 <code>Presenter</code> 层，负责绑定 <code>Model</code> 层和 <code>View</code> 层，相比于 <code>MVP</code> 增加了双向绑定机制。</p>
<blockquote>
<p><code>MVVM</code> 模式的特征是 <code>ViewModel</code> 层和 <code>View</code> 层采用双向绑定的形式（Binding），<code>View</code> 层的变动，将自动反映在 <code>ViewModel</code> 层，反之亦然。</p>
</blockquote>
<ul>
<li>但是双向绑定给调试和错误定位带来困难，<code>View</code> 层的异常可能是 <code>View</code> 的代码有问题，也有可能是 <code>Model</code> 层的问题。数据绑定使得一个位置的 <code>Bug</code> 被传递到别的位置，要定位原始出问题的地方就变得不那么容易了。</li>
<li>对简单<code>UI</code> 来说，实现 <code>MVVM</code> 模式的开销是不必要的，而对于大型应用来说，引入 MVVM 模式则会节约大量手动更新视图的复杂过程，是否使用，还是看使用场景。</li>
</ul>
<p>这是为什么呢，因为 <code>MVVM</code> 模式要求 <code>Model</code> 层和 <code>View</code> 层完全解耦，但是由于 <code>Vue</code> 还提供了 <code>ref</code> 这样的 <code>API</code>，使得 <code>Model</code> 也可以直接持有 <code>View</code>：</p>
<p>但是大多数帖子都说直接称呼 <code>Vue</code> 为 <code>MVVM</code> 框架，可见这些模式的划分也不是那么严格。</p>

    </div>

    
    
    
      
<div>
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
</div>
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/10/18/js%E5%87%BD%E6%95%B0%E6%89%8B%E5%86%99%EF%BC%88%E6%97%A7%E7%89%88%EF%BC%89/" rel="prev" title="js函数手写（旧版）">
      <i class="fa fa-chevron-left"></i> js函数手写（旧版）
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/10/20/Webpack%E9%9D%A2%E8%AF%95%E9%A2%98/" rel="next" title="Weppack面试题整理">
      Weppack面试题整理 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%B8%B8%E8%A7%81%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F"><span class="nav-text">常见设计模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E5%AD%A6%E4%B9%A0%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%9F"><span class="nav-text">1.为什么要学习设计模式？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E4%BB%80%E4%B9%88%E6%98%AF%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E3%80%82"><span class="nav-text">2.什么是设计模式。</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E7%9A%84%E5%8F%91%E5%B1%95%E5%8E%86%E5%8F%B2"><span class="nav-text">3.设计模式的发展历史</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E5%88%86%E7%B1%BB"><span class="nav-text">4.设计模式分类</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E5%9F%BA%E7%A1%80%E7%AF%87"><span class="nav-text">一、基础篇</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#this%E3%80%81new%E3%80%81bind%E3%80%81call%E3%80%81apply"><span class="nav-text">this、new、bind、call、apply</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-this-%E6%8C%87%E5%90%91%E7%9A%84%E7%B1%BB%E5%9E%8B"><span class="nav-text">1. this 指向的类型</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#this-%E5%9C%A8%E5%87%BD%E6%95%B0%E7%9A%84%E6%8C%87%E5%90%91%E6%9C%89%E4%BB%A5%E4%B8%8B%E5%87%A0%E7%A7%8D%E5%9C%BA%E6%99%AF%EF%BC%9A"><span class="nav-text">this 在函数的指向有以下几种场景：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-new-%E7%BB%91%E5%AE%9A"><span class="nav-text">1.1 new 绑定</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-%E6%98%BE%E5%BC%8F%E7%BB%91%E5%AE%9A"><span class="nav-text">1.2 显式绑定</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-%E9%9A%90%E5%BC%8F%E7%BB%91%E5%AE%9A"><span class="nav-text">1.3 隐式绑定</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-4-%E9%BB%98%E8%AE%A4%E7%BB%91%E5%AE%9A"><span class="nav-text">1.4 默认绑定</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-this-%E7%BB%91%E5%AE%9A%E7%9A%84%E4%BC%98%E5%85%88%E7%BA%A7"><span class="nav-text">2. this 绑定的优先级</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-%E7%AE%AD%E5%A4%B4%E5%87%BD%E6%95%B0%E4%B8%AD%E7%9A%84-this"><span class="nav-text">3. 箭头函数中的 this</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-%E4%B8%80%E4%B8%AA-this-%E7%9A%84%E5%B0%8F%E7%BB%83%E4%B9%A0"><span class="nav-text">4. 一个 this 的小练习</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%97%AD%E5%8C%85%E4%B8%8E%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0"><span class="nav-text">闭包与高阶函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E9%97%AD%E5%8C%85"><span class="nav-text">1. 闭包</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-%E4%BB%80%E4%B9%88%E6%98%AF%E9%97%AD%E5%8C%85"><span class="nav-text">1.1 什么是闭包</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-%E5%88%A9%E7%94%A8%E9%97%AD%E5%8C%85%E5%AE%9E%E7%8E%B0%E7%BB%93%E6%9E%9C%E7%BC%93%E5%AD%98%EF%BC%88%E5%A4%87%E5%BF%98%E6%A8%A1%E5%BC%8F%EF%BC%89"><span class="nav-text">1.2 利用闭包实现结果缓存（备忘模式）</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0"><span class="nav-text">2. 高阶函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-%E5%87%BD%E6%95%B0%E4%BD%9C%E4%B8%BA%E5%8F%82%E6%95%B0"><span class="nav-text">2.1 函数作为参数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-%E5%87%BD%E6%95%B0%E4%BD%9C%E4%B8%BA%E8%BF%94%E5%9B%9E%E5%80%BC"><span class="nav-text">2.2 函数作为返回值</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-%E6%9F%AF%E9%87%8C%E5%8C%96"><span class="nav-text">1. 柯里化</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-%E5%8F%8D%E6%9F%AF%E9%87%8C%E5%8C%96"><span class="nav-text">2. 反柯里化</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-%E5%81%8F%E5%87%BD%E6%95%B0"><span class="nav-text">3. 偏函数</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99"><span class="nav-text">设计原则</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E5%8D%95%E4%B8%80%E8%81%8C%E8%B4%A3%E5%8E%9F%E5%88%99-SRP"><span class="nav-text">1. 单一职责原则 SRP</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E5%BC%80%E6%94%BE%E5%B0%81%E9%97%AD%E5%8E%9F%E5%88%99-OCP"><span class="nav-text">2. 开放封闭原则 OCP</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-%E6%9C%80%E5%B0%91%E7%9F%A5%E8%AF%86%E5%8E%9F%E5%88%99-LKP"><span class="nav-text">3. 最少知识原则 LKP</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%88%9B%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text">二、创建型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text">单例模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F"><span class="nav-text">工厂模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F"><span class="nav-text">抽象工厂模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text">建造者模式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E7%BB%93%E6%9E%84%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text">三、结构型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%A3%E7%90%86%E6%A8%A1%E5%BC%8F"><span class="nav-text">代理模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%AB%E5%85%83%E6%A8%A1%E5%BC%8F"><span class="nav-text">享元模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F"><span class="nav-text">适配器模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%A3%85%E9%A5%B0%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text">装饰者模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%96%E8%A7%82%E6%A8%A1%E5%BC%8F"><span class="nav-text">外观模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BB%84%E5%90%88%E6%A8%A1%E5%BC%8F"><span class="nav-text">组合模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A1%A5%E6%8E%A5%E6%A8%A1%E5%BC%8F"><span class="nav-text">桥接模式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9B%9B%E3%80%81%E8%A1%8C%E4%B8%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text">四、行为型模式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%94%E3%80%81%E5%85%B6%E4%BB%96%E6%A8%A1%E5%BC%8F"><span class="nav-text">五、其他模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#MVC%E3%80%81MVP%E3%80%81MVVM"><span class="nav-text">MVC、MVP、MVVM</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-MVC-%EF%BC%88Model-View-Controller%EF%BC%89"><span class="nav-text">1. MVC （Model View Controller）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-MVP-%EF%BC%88Model-View-Presenter%EF%BC%89"><span class="nav-text">2. MVP （Model View Presenter）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-MVVM-%EF%BC%88Model-View-ViewModel%EF%BC%89"><span class="nav-text">3. MVVM （Model View ViewModel）</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="hxy"
      src="/images/Robben.gif">
  <p class="site-author-name" itemprop="name">hxy</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">80</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">120</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/huxingyi1997" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;huxingyi1997" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:huxingyi1997@zju.edu.cn" title="E-Mail → mailto:huxingyi1997@zju.edu.cn" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-frog"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hxy</span>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共1039.2k字</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'pQsO3ySbU4VtWN2j1FLA74Ha-gzGzoHsz',
      appKey     : 'QYacMDY2VY7Wazprg1X6FiUv',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

  
  <!-- 动态背景特效 -->
  <!-- 樱花特效 -->
    <script async src="/js/src/sakura.js"></script>
    <script async src="/js/src/fairyDustCursor.js"></script>
</body>
</html>
